Skip to content Skip to sidebar Skip to footer

Different Background For A Button's States In Kotlin

I have a button in my project that works like this: The button has 3 different designs for each state - disabled (state_enabled='false'), enabled, pressed. This button remains di

Solution 1:

Maybe you should set a default color.

<itemandroid:drawable="@drawable/background_blue"android:state_enabled="true" /><itemandroid:drawable="@drawable/background_blue_white"android:state_enabled="false" /><itemandroid:drawable="@drawable/background_green"android:state_pressed="true" /><itemandroid:drawable="@drawable/background_blue" />

The default color without any "pressed" and "enabled" drawable.

Solution 2:

A selector will select the first item that matches the current state.

From the documentation:

Note: Remember that Android applies the first item in the state list that matches the current state of the object. So, if the first item in the list contains none of the state attributes above, then it is applied every time, which is why your default value should always be last (as demonstrated in the following example).

A pressed button is also enabled, so your selector still picks the 'enabled' state over the 'pressed' state because it was defined earlier.

You can try adjusting the ordering to fix your issue:

<selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:drawable="@drawable/background_green"android:state_pressed="true" /><!-- pressed --><itemandroid:drawable="@drawable/background_blue_white"android:state_enabled="false" /><!-- disabled --><itemandroid:drawable="@drawable/background_blue" /><!-- default --></selector>

To avoid confusion like this in the future a good approach is to be more specific such so that only one item matches at a time. These items use the original order but only one will match at a time:

<itemandroid:drawable="@drawable/background_blue"android:state_enabled="true"android:state_pressed="false" /><itemandroid:drawable="@drawable/background_blue_white"android:state_enabled="false"android:state_pressed="false"  /><itemandroid:drawable="@drawable/background_green"android:state_enabled="true"android:state_pressed="true" />

(Note that it would be better to have a default at the bottom because now it would technically be possible that none match)

Solution 3:

You should make your button clickable for that.

You can make it with button.setClickable(true)(If you are using JAVA) or you can add in your .xml where you have android:clickable="true".

If you are using Kotlin then add button.clickable = true instead of the first solution with Java code.

Update: You should try a this thing as well. Follow this answer might be helpful. As per that answer, you should keep all states into proper order. I don't know why but I think it should help.

Try this and let me know if it will help you. Thanks & Happy coding..!

Post a Comment for "Different Background For A Button's States In Kotlin"