从公共资源为自定义ViewGroup的多个组件创建StateListDrawable

Sou*_*ion 4 android statelistdrawable

我创建了一个扩展ViewGroup的类.此MyCustomViewGroup类的一个功能是充当嵌套类MyButton的容器,该类扩展了Button.

我以正常方式从自定义AttributeSet设置MyCustomViewGroup的自定义属性.其中一个属性定义StateListDrawable以用于MyButton嵌套类的实例的背景.我将它存储在类变量mMyButtonBackground中.

public class MyCustomViewGroup extends ViewGroup {
    private Drawable mMyButtonBackground;
    ...
Run Code Online (Sandbox Code Playgroud)

每次我在MyCustomViewGroup中创建MyButton的新实例时,我都会设置它的背景.

    MyButton myButton = new MyButton(context);
    myButton.setBackground(mMyButtonBackground);
Run Code Online (Sandbox Code Playgroud)

在运行时,StateListDrawable似乎只适用于最近添加的MyButton实例.

例如,假设我在MyCustomViewGroup中创建了4个MyButton实例.如果我单击MyButton number 4,它的背景会发生变化,如StateListDrawable中所定义.如果我点击MyButton 1到3,他们的背景不会改变,但MyButton编号为4.

从逻辑上讲,这表明它是一个可变性问题.所有MyButton实例共享存储在mMyButtonBackground中的相同StateListDrawable.考虑到这一点,我尝试过:

    MyButton myButton = new MyButton(context);
    Drawable myButtonBackground = mMyButtonBackground.mutate();
    myButton.setBackground(myButtonBackground);
Run Code Online (Sandbox Code Playgroud)

但这并没有解决问题.我也试过将它专门用作StateListDrawable:

    MyButton myButton = new MyButton(context);
    StateListDrawable myButtonBackground = (StateListDrawable)mMyButtonBackground.mutate();
    myButton.setBackground(myButtonBackground);
Run Code Online (Sandbox Code Playgroud)

这也没有解决问题.在我试图解决这个问题的研究中,我已经阅读了Romain Guy关于Drawable突变的这篇文章.我原以为,由于StateListDrawable是Drawable的子类,我应该可以应用相同的方法,但我似乎无法让它工作.我错过了什么?

psk*_*ink 8

你无法与多个视图共享一个SLD实例,每个视图需要一个SLD,抱歉