How to specify background color in Color State List Resources?
I had this exact problem. It looks to me like android:background
doesn't work with Color State Lists. I got around this by creating a State List Drawable instead (individual colors can be used as drawables in the State List).
To use your example, create a file res/drawable/button_test_background.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/pressed_color"/>
<item android:state_focused="true" android:drawable="@color/focused_color"/>
<item android:drawable="@color/default_color"/>
</selector>
Note the use of android:drawable
instead of android:color
. Android will use the color resource and make a drawable out of it. To finish this off, you need to add the color resources to your res/values/colors.xml
file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
...
<color name="pressed_color">#f0f</color>
<color name="focused_color">#ff0</color>
<color name="default_color">#000</color>
...
</resources>
You would then refer to this drawable using @drawable/button_test_background
instead of @color/button_test_color
.
So, in summary, the Color State List works fine for android:textColor
, but for android:background
the State List Drawable method above is needed.