Search code examples
androidxmlkotlinbuttondrawable

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 disabled if no file is selected, and has a particular design for it. Although, when file is selected, this button becomes enabled and switches to a different design. And the button's highlight color is possible to see every time when the button is enabled and pressed.

What I have tried so far:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

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

</selector>

What I want to have is:

  1. Disabled: Click here to see the disabled button - means I can't click on it unless I have a file selected.

  2. Enabled: Click here to see the enabled button] - means I have selected a file.

  3. Pressed: enter image description here - means if the button is enabled and I press on it.

state_enabled="false" and state_enabled="true" work just fine, whereas state_pressed="true" doesn't work at all. What do you think I am doing wrong?

Please, let me know if my explanations are complicated - I will do my best to describe the problem to make it be as understandable as possible. Thank you so much. Have a nice day!


Solution

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