Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android:state_pressed is not working

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>
like image 422
Abdurakhmon Avatar asked Oct 17 '25 18:10

Abdurakhmon


2 Answers

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>
like image 58
yotam hadas Avatar answered Oct 20 '25 07:10

yotam hadas


    <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.

like image 42
Rathiga Jesika Avatar answered Oct 20 '25 08:10

Rathiga Jesika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!