Android : How to update the selector(StateListDrawable) programmatically

Mani picture Mani · Feb 23, 2011 · Viewed 52.6k times · Source

I want to update the selector for a button programmatically.

I can do this with the xml file which is given below

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_enabled="false"
         android:drawable="@drawable/btn_off" />
   <item android:state_pressed="true"
         android:state_enabled="true" 
         android:drawable="@drawable/btn_off" />
   <item android:state_focused="true"
         android:state_enabled="true" 
         android:drawable="@drawable/btn_on" />
   <item android:state_enabled="true" 
         android:drawable="@drawable/btn_on" />
</selector>

I want to do the same thing programmatically. I have tried something like given below

private StateListDrawable setImageButtonState(int index)
{
    StateListDrawable states = new StateListDrawable();

    states.addState(new int[] {android.R.attr.stateNotNeeded},R.drawable.btn_off); 
    states.addState(new int[] {android.R.attr.state_pressed, android.R.attr.state_enabled},R.drawable.btn_off);
    states.addState(new int[] {android.R.attr.state_focused, android.R.attr.state_enabled},R.drawable.btn_on);
    states.addState(new int[] {android.R.attr.state_enabled},R.drawable.btn_on);

    return states;
}

but it didnt work.

And how to set android:state_enabled="false" or android:state_enabled="true" programatically.

Answer

Zsolt picture Zsolt · Mar 20, 2011

You need to use the negative value of the needed state. E.g.:

states.addState(new int[] {-android.R.attr.state_enabled},R.drawable.btn_disabled);

Notice the "-" sign before android.R.attr.state_enabled.