XML 定義
<shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FFFF00" />
<padding android:left="7dp" android:top="7dp" android:right="7dp" android:bottom="7dp" />
</shape>
代碼動態修改
// 獲取 View 背景
ShapeDrawable bg = (ShapeDrawable) textView.getBackground();
// 修改顏色
bg.getPaint().setColor(Color.RED); // 或 Color.parseColor("#FF0000")
// 觸發重繪
textView.invalidate();
注意事項
- 背景必須是
ShapeDrawable,若 XML 根標籤是 <selector> 或 <layer-list> 需先取得子 Drawable
mutate():若多個 View 共用同一 Drawable 資源,修改前呼叫 bg.mutate() 避免影響其他 View
- API 21+ 可用
DrawableCompat.setTint() 統一著色
完整範例
Drawable bg = textView.getBackground();
if (bg instanceof ShapeDrawable) {
((ShapeDrawable) bg.mutate()).getPaint().setColor(newColor);
} else if (bg instanceof GradientDrawable) {
((GradientDrawable) bg.mutate()).setColor(newColor);
}
textView.invalidate();