关于改变一个控件里的Drawable属性的时候其他控件也一起变化的问题

  • 说明:本文源于熊老师,如需转载请带上链接或注明出处!

android中从同一个资源文件中加载出来的drawable会共享状态,如果你加载出来多个drawable,当改变了其中一个的状态时,其他drawable的状态也会相应改变。

举个栗子哈哈

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:background="@color/colorPrimary"
android:onClick="button1"
android:text="button1" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:background="@color/colorPrimary"
android:onClick="button2"
android:text="button2" />
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
findViewById(R.id.button1).getBackground().setAlpha(0);
}
/**
* Make this drawable mutable. This operation cannot be reversed. A mutable
* drawable is guaranteed to not share its state with any other drawable.
* This is especially useful when you need to modify properties of drawables
* loaded from resources. By default, all drawables instances loaded from
* the same resource share a common state; if you modify the state of one
* instance, all the other instances will receive the same modification.
*
* Calling this method on a mutable Drawable will have no effect.
*

如果把这个drawable变为mutate drawable后,这个drawable就不会与其他drawable共享状态。

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
findViewById(R.id.button1).mutate().getBackground().setAlpha(0);
}

这样设置就没问题了,当然也可以一开始就不要将它们的背景资源文件设成同一个,也可以解决