I want to update the selector for a button programmatically.
I can do this with the xml file which is given below
Not enough rep to comment but the accepted answer did not work for me.
My goal was for designers to set enabled, disabled, and pressed background colors on some button. I intended for them to use it to test colors on different displays.
I noticed some other people mentioned it did not work for them either.
The states that need to be defined are
Here is some code that will give you an idea of the states. I am using Color.Parse() to generate ints for the colors then I pass them to this method to get the StateListDrawable.
private StateListDrawable createDrawable(int enabled, int pressed, int disabled) {
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[] { -android.R.attr.state_pressed, android.R.attr.state_enabled }, new ColorDrawable(enabled));
stateListDrawable.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, new ColorDrawable(pressed));
stateListDrawable.addState(new int[] { -android.R.attr.state_enabled }, new ColorDrawable(disabled));
return stateListDrawable;
}