Android開發中遇到需要設置一個shape文件A做爲背景顏色,在項目中需要動態的更改背景顏色,於是乎想到了使用GradientDrawable這個類來改變控件的背景顏色,使用起來很簡單,前提是view的background屬性爲shape A
GradientDrawable gd = view.getBackground();
gd.setColor();
這樣就可以實現動態改變shape的填充色
坑來了
因爲A資源不止在一個地方使用,所以在B頁面將A資源的填充色改變之後,訪問其他頁面的時候,發現使用A資源爲背景顏色的控件,背景顏色都變成了在B界面更改的顏色,所以這個GradientDrawable類在使用中,儘量避免將更改了填充色shape資源,在項目中的重複引用!
原因
GradientDrawable.setColor源碼有說明
用一個單一的顏色代替一個梯度變化,來更改drawable資源
更改的顏色會影響drawable從資源加載的所有實例,建議在更改顏色之前調用
/** * Changes this drawable to use a single color instead of a gradient. * <p> * <strong>Note</strong>: changing color will affect all instances of a * drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing the color. * * @param argb The color used to fill the shape * * @see #mutate() * @see #setColors(int[]) * @see #getColor */ public void setColor(@ColorInt int argb) { mGradientState.setSolidColors(ColorStateList.valueOf(argb)); mFillPaint.setColor(argb); invalidateSelf(); }