I created a class that extends ViewGroup. One of the functions of this class, MyCustomViewGroup, acts as a container for the nested class MyButton, which extends Button.
I am setting custom properties for MyCustomViewGroup from a custom AttributeSet in the usual way. One of the attributes defines StateListDrawable for use against the background of instances of the nested class MyButton. I store this in the class variable mMyButtonBackground.
public class MyCustomViewGroup extends ViewGroup { private Drawable mMyButtonBackground; ...
Every time I create a new instance of MyButton in MyCustomViewGroup, I set it as a background.
MyButton myButton = new MyButton(context); myButton.setBackground(mMyButtonBackground);
At run time, StateListDrawable seems to work only for the last instance of MyButton added.
For example, I create 4 instances of MyButton in MyCustomViewGroup. If I click on MyButton number 4, this will change the background as defined in StateListDrawable. If I click on MyButton from 1 to 3, their background will not change, but MyButton number 4. does.
Logically, this suggests that this is a problem with variability. All MyButton instances use the same StateListDrawable stored in mMyButtonBackground. Given this, I tried:
MyButton myButton = new MyButton(context); Drawable myButtonBackground = mMyButtonBackground.mutate(); myButton.setBackground(myButtonBackground);
This did not solve the problem. I also tried using it as a StateListDrawable:
MyButton myButton = new MyButton(context); StateListDrawable myButtonBackground = (StateListDrawable)mMyButtonBackground.mutate(); myButton.setBackground(myButtonBackground);
This also did not solve the problem. In my studies trying to solve this problem, I read this article by Romain Gai about Drawable mutations . I would think that since StateListDrawable is a subclass of Drawable, I should be able to take the same approach, but I can't get it to work. What am I missing?