chRyNaN chRyNaN - 6 months ago 22
Java Question

How to set custom button state background color?

I have a button which contains a drawable and text. I want the background of the button to be different than the normal one provided (preferably a plain color). This works fine, I simply use the

attribute in the XML file and assign the color accordingly. However, I want the the background to change to a different color when selected or focused (state selector).

I attempted to create a selector in a drawable folder with the defined colors (which works well when working with the text of a button), like so:

<selector xmlns:android="">
<item android:state_focused="true" android:state_pressed="false" android:color="@color/green" />
<item android:state_focused="true" android:state_pressed="true" android:color="@color/green" />
<item android:state_focused="false" android:state_pressed="true" android:color="@color/green" />
<item android:color="@color/white" />

and set this xml as the
attribute, like so:


but this causes a force close stating:

Caused by: android.content.res.Resources$NotFoundException: File res/drawable/button_state.xml from drawable resource ID #0x7f020070

but the resource is there. Can you not customize the background state? If you can, how? or what am I doing wrong? Thanks for the help!


The xml you posted is suitable for a color state list, not a state list drawable. Try this instead:

<selector xmlns:android="">
    <item android:state_focused="true" android:state_pressed="false" >
        <shape><solid android:color="@color/green"/></shape>
    . . .

Alternatively, put your existing file into res/color and use it as you would any other color. However, I don't remember if you can use a color state list directly as a background for a view.