阅读量:1
在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就可以根据状态动态变化了。注意,这些方法需要在主线程中执行。
以上就是关于“android colorprimary怎样实现动态变化”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm