android:state_pressed is not working

7.7k views Asked by At

I have the following XML code in res/drawable and I set button background to this drawable. However when I pressed the button it is not not changing the color. Thanks for help

<item android:state_enabled="false"
    android:drawable="@color/colorAccent">
</item>

<item android:state_enabled="true"
    android:drawable="@color/colorPrimary">
</item>

<item
    android:state_selected="false"
    android:state_pressed="true"
    android:drawable="@color/black">
</item>
3

There are 3 answers

0
Rathiga Jesika On BEST ANSWER
    <selector>
    <item android:state_pressed="true" android:drawable="#EDCFE9"/>
    <item android:state_selected="true" android:drawable="#EDCFE9"/>
    <item android:drawable="#603F86"/>
    </selector>

This will change the button color on button press.

Order matters when specifying the selector fields - whichever selector it matches first, going from top to bottom, will be the one displayed. The default button state should always be specified last.

0
santoshnisal007 On

Create a new drawable with below code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/pink"/> <!-- pressed state -->
<item android:drawable="@color/blue"/> <!-- default state -->
</selector>

Add the below colors into values > colors.xml file

<color name="blue">#49B8C7</color>
<color name="pink">#FF8EB9</color>
2
yotam hadas On

well you need to remember that android read line after line and returnthe first true statment. because you have enable false / true items BEFORE the state_Selected it will always choose enabled = false / true item. simply move your bottum code before the "state_enabled" like so:

<item
    android:state_selected="false"
    android:state_pressed="true"
    android:drawable="@color/black">
</item>

<item android:state_enabled="false"
    android:drawable="@color/colorAccent">
</item>

<item android:state_enabled="true"
    android:drawable="@color/colorPrimary">
</item>