Android:使用选择器更改按钮的背景图像和颜色 [英] Android : Using selector to change button background image and color
问题描述
我有一个按钮,将其背景设置为特定的selector
.
选择器当前更改按钮背景,并将图像更改为背景.
我还希望更改背景色(图像是带有透明空间的图标).
这是选择器:
I have a button I set its background to specific selector
.
The selector currently changes the button background and changed an image as the background.
I also want the background color to be changed (the image is icon with transparent space around).
This is the selector :
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- default -->
<item
android:state_pressed="false"
android:state_focused="false"
android:drawable="@drawable/menu_button_collapsed" >
</item>
<!-- button focused -->
<item
android:state_pressed="false"
android:state_focused="true"
android:drawable="@drawable/menu_button_collapsed_highlight"
android:drawable="@drawable/button_background" >
</item>
<!-- button pressed -->
<item
android:state_pressed="true"
android:state_focused="false"
android:drawable="@drawable/menu_button_collapsed_highlight"
android:drawable="@drawable/button_background" >
</item>
</selector>
如您所见,我两次设置了drawable
属性,这是非法的,但这实际上是我想要的.
注意@drawable/button_background
只是一种颜色
As you can see, I set the drawable
attribute twice, which is illegal, but this is what I want actually.
Notice @drawable/button_background
is just a color
推荐答案
创建新的<layer-list>
可绘制对象
custom_button.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Your background color goes first -->
<item
android:id="@android:id/background"
android:drawable="@drawable/button_background" />
<!-- Your button icon image -->
<item
android:id="@android:id/button_image"
android:drawable="@drawable/menu_button_collapsed_highlight" />
</layer-list>
并在选择器可绘制文件中引用它
And reference it in your selector drawable file
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- default -->
<item
android:state_pressed="false"
android:state_focused="false"
android:drawable="@drawable/menu_button_collapsed"
/>
<!-- button focused -->
<item
android:state_pressed="false"
android:state_focused="true"
android:drawable="@drawable/custom_button"
/>
<!-- button pressed -->
<item
android:state_pressed="true"
android:state_focused="false"
android:drawable="@drawable/custom_button"
/>
</selector>
这篇关于Android:使用选择器更改按钮的背景图像和颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!