要動態(tài)使用Android的ColorStateList,可以通過代碼創(chuàng)建一個ColorStateList對象,并將其應(yīng)用到View或Drawable對象上。以下是一個示例代碼:
// 創(chuàng)建一個ColorStateList對象
int[][] states = new int[][] {
new int[] {android.R.attr.state_pressed},
new int[] {android.R.attr.state_focused},
new int[] {}
};
int[] colors = new int[] {
Color.RED,
Color.GREEN,
Color.BLUE
};
ColorStateList colorStateList = new ColorStateList(states, colors);
// 應(yīng)用ColorStateList到一個Button上
Button button = findViewById(R.id.button);
button.setTextColor(colorStateList);
在這個例子中,我們首先創(chuàng)建一個包含不同狀態(tài)和顏色的ColorStateList對象。然后,我們將這個ColorStateList對象應(yīng)用到一個Button的文本顏色上。根據(jù)Button的不同狀態(tài)(按下、獲取焦點、普通狀態(tài)),文本顏色會自動根據(jù)ColorStateList中定義的顏色進行切換。