I hope anybody can help me with this frustrating issue I am currently experiencing: I try to programmatically add a StateListDrawable to one of my buttons:
final Button btn_footer = (Button)findViewById(R.id.btn_footer);
btn_footer.setBackground(new MyStateListDrawable(this));
The class MyStateListDrawable itself adds two LayerDrawables; one for the regular state of the button and one shown when the button is disabled or in a pressed state.
public class MyStateListDrawable extends StateListDrawable {
public MyStateListDrawable(Context c) {
addState(new int[] {-android.R.attr.state_pressed, -android.R.attr.state_enabled}, getStateDrawable(c,false));
addState(new int[] {android.R.attr.state_pressed, android.R.attr.state_enabled}, getStateDrawable(c,true));
}
...
The LayerDrawables are created in the method getStateDrawable of the MyStateListDrawable class:
...
public Drawable getStateDrawable(Context c, boolean isTransp){
GradientDrawable shadowGradient = new GradientDrawable();
GradientDrawable buttonGradient = new GradientDrawable();
[...]
Drawable[] drawableArray = {shadowGradient, buttonGradient};
LayerDrawable layerDrawable = new LayerDrawable(drawableArray);
if(isTransp)
layerDrawable.setAlpha(0x88);
return layerDrawable;
}
}
Now, when I run the activity the default state of the button is rendered properly, but if I try to disable or press the button the style does not change to the second LayerDrawable defined . When I add the properties via XML-files to my button they work just fine, but I have currently already 30+ XML-files (each with little style variations regarding color or size) and it would be very nice to create them dynamically in one class for all buttons. Does anybody know what is causing this issue?
I finally found some time to come back to this issue. After trying a lot of different possibilities I got it working through adding the same drawable individually (!) for each state (when the button is pressed and when it is disabled). The other states are covered through a drawable added with a wild card for the other states.
public MyStateListDrawable(Context c) {
addState(new int[] {android.R.attr.state_pressed}, getStateDrawable(c, true));
addState(new int[] {-android.R.attr.state_enabled}, getStateDrawable(c, true));
addState(StateSet.WILD_CARD, getStateDrawable(c, false));
}
....