Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : How to update the selector(StateListDrawable) programmatically

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.

like image 694
Mani Avatar asked Feb 23 '11 15:02

Mani


1 Answers

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.

like image 125
Zsolt Avatar answered Sep 21 '22 20:09

Zsolt