在Android中,要使colorPrimary
动态变化,可以通过编程方式更改主题属性或者使用ColorStateList
来实现。以下是两种实现方法:
方法1:编程方式更改主题属性
在代码中,你可以通过以下步骤动态更改colorPrimary
:
TypedArray typedArray = getTheme().obtainStyledAttributes(new int[]{android.R.attr.colorPrimary});
int colorPrimary = typedArray.getColor(0, 0);
typedArray.recycle();
colorPrimary
值:int newColorPrimary = getResources().getColor(R.color.new_color_primary);
colorPrimary
值:TypedArray typedArray = getTheme().obtainStyledAttributes(new int[]{android.R.attr.colorPrimary});
typedArray.setColor(0, newColorPrimary);
setTheme(getTheme()); // 应用新的主题
typedArray.recycle();
方法2:使用ColorStateList
ColorStateList
对象,定义不同状态的颜色:ColorStateList colorStateList = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_enabled}, // 状态为enabled时的颜色
new int[]{-android.R.attr.state_enabled} // 状态为not enabled时的颜色
},
new int[]{
ContextCompat.getColor(this, R.color.color_primary_enabled), // 状态为enabled时的颜色值
ContextCompat.getColor(this, R.color.color_primary_not_enabled) // 状态为not enabled时的颜色值
}
);
ColorStateList
到colorPrimary
:setTheme(new Theme().applyStyle(R.style.AppTheme, true));
TypedArray typedArray = getTheme().obtainStyledAttributes(new int[]{android.R.attr.colorPrimary});
typedArray.setColor(0, colorStateList.getDefaultColor());
setTheme(getTheme()); // 应用新的主题
typedArray.recycle();
这样,colorPrimary
就可以根据状态动态变化了。注意,这些方法需要在主线程中执行。