Android中的复杂自定义按钮状态

时间:2012-04-09 15:06:10

标签: android android-layout button

在我目前的项目中,我正在使用API​​ 10构建一个应该看起来像ICS App的应用程序。 由于我的GUI不是很复杂,我可以手动构建这个,但是按钮状态有一些问题。

我google了很多,发现任何对我都没有用的东西,所以我会感激任何帮助;)

我设计了一个带有谷歌ICS股票图标的操作栏。例如,当有人触摸搜索放大镜图标时,其周围有8dp填充,它的背景颜色应该更改为定义的高亮颜色值。

所以现在你可能会建议一个选择器drawable。但我的情况是:我有一个 icon-drawable ,其背景颜色,我想更改。我不想更改图标,因此我无法从selector-xml更改backgroundcolor,这不起作用。 (我以为我可以用我的图标静态bg颜色设置多个drawable-xml,这样我可以用一个选择器引用那些不同颜色的图标,但是因为一个shape-drawable-xml不能有一个源和一个bitmap-drawable-xml不能有背景颜色,这不是溶剂。)

如果我尝试使用以下方法更改onclick-listener(也尝试使用onTouch)中的背景颜色:

ImageButton searchIcon = (ImageButton) findViewById(R.id.upper_actionbar_icon_search);
            searchIcon.setBackgroundColor(R.color.android_ics_blue_light);

Icon获得深灰色bg颜色。对于任何其他颜色也是如此,尽管ImageButton上没有任何颜色。我也尝试过ImageView。

所以有人可以向我解释我该如何定义一个没有任何黑客的突出显示的bg彩色图像(默认消失的图像位于图标上方并且设置为可见的onclick)。 非常感谢!!

1 个答案:

答案 0 :(得分:2)

好的解决方案很简单。

给自己写一个可绘制的选择器,如下所示:

<?xml version="1.0" encoding="utf-8"?>

<item android:state_selected="true">
    <shape android:shape="rectangle">
        <solid android:color="@color/android_ics_blue_light"/>
    </shape>
</item>


<item android:state_pressed="true">
    <shape android:shape="rectangle">
        <solid android:color="@color/android_ics_blue_light"/>
    </shape>
</item>

 <item>
    <shape android:shape="rectangle">
        <solid android:color="@color/light_grey"/>
    </shape>
</item>

在您的ImageButton代码中,将您的图标定义为src,将新的drawable定义为背景,如下所示:

<ImageButton
                <!-- ... -->
                android:src="@drawable/icon_search" 
                android:background="@drawable/actionbar_ontouch"

                />

像魅力一样!