我有一个按钮,将其背景设置为特定的选择器.
选择器当前更改按钮背景,并将图像更改为背景.
我还希望更改背景色(图像是带有透明空间的图标).
这是选择器:
<?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只是一种颜色
解决方法:
创建一个新的< 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>
并在您的选择器可绘制文件中引用它
<?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>