Search code examples
javaandroidcheckboxdrawableandroid-custom-view

Custom button drawable state_pressed and state_checked not working on CheckBox or RadioButton - Android


I am setting custom drawable to the checkbox button,
But only android:state_checked="true" and android:state_checked="false" seem to work.
Other states aren't working.

I am unable to set a custom drawable on pressed state.

This is the selector I am using:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/radio_btn_selected" />
    <item android:state_checked="false" android:drawable="@drawable/radio_btn_normal" />
    <item android:state_pressed="true"  android:drawable="@drawable/radio_btn_pressed" />
    <item android:state_focused="true"  android:drawable="@drawable/radio_btn_pressed" />
    <item android:drawable="@drawable/radio_btn_normal"/> <!-- default -->
</selector>

This is how I am setting it to radio button:

radioButton.setButtonDrawable(R.drawable.radio_btn_selectors);

Solution

  • android:state_pressed="true" and android:state_focused="true" are not working because of the ordering in which you declared various states. Whenever you declare a drawable like this, system will goes from top to bottom and if a state is matched, it doesn't look for the other ones and applies the changes based on the very first selection. I think here android:state_checked="false" condition might be executing instead of android:state_pressed="true" and android:state_focused="true". So move android:state_checked="false" to the bottom and then try.