如果有多個控件同時使用某一個圖片資源,並且要改變該資源的狀態時就需要用mutate方法。使用mutate是爲了更改一個資源的狀態時,其餘引用該資源的控件不會也更改狀態。
默認情況下,所有的從同一資源(R.drawable.***)加載的drawable實例都共享一個共用的狀態,如果你更改一個實例的狀態,其餘的實例都會接收到相同的通知。使用mutate可以使該drawable狀態不定。一個不定狀態的drawable不會共享狀態。
Drawable bkDrawable = this.getBackground().mutate();
if (null != bkDrawable)
{
if (enable)
{
bkDrawable.clearColorFilter();
}
else
{
//通過setColorFilter來改變drawable的狀態,如果不用mutate,其餘引用了該背景
的資源也會被設置這個ColorFilter
bkDrawable.setColorFilter(m_disableColor, PorterDuff.Mode.DST_OUT);
}
this.setBackgroundDrawable(bkDrawable);
}