Java – how to set the background color of custom button status?
I have a button that contains drawable and text I hope the background of the button is different from the normal background provided (preferably solid color) This works well. I just use the Android: background attribute in the XML file and assign colors accordingly However, I want the background to change to a different color when selecting or focusing (status selector)
I tried to create a selector in a drawable folder with defined colors (works well when processing button text), as follows:
<selector xmlns:android="http://schemas.android.com/apk/res/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" /> </selector>
And set this XML as the Android: background attribute, as shown below:
android:background="@drawable/button_state"
But this leads to a power off note:
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/button_state.xml from drawable resource ID #0x7f020070
But the resources are there Can you not customize the background state? What if I could? Or did I do something wrong? Thank you for your help!
Solution
The XML you publish applies to the color state list, not the status list drawable Try this:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" > <shape><solid android:color="@color/green"/></shape> </item> . . . </selector>
Or, put the existing file in RES / color and use it like any other color However, I don't remember whether you can directly use the color status list as the background of the view