谷歌引入了材料3,允许用户选择一种颜色来申请整个系统主题,但他们的文档并不清楚,也没有提到如何通过编程获取当前的颜色,比如更改视图的背景色或文本颜色。
例如:view.setBackgroundColor(Material3.getPrimaryColor());
当然,Material3.getPrimaryColor()并不存在,它只是我所需要的一个例子。
任何帮助都是非常感谢的,谢谢。
发布于 2022-03-07 01:10:38
首先,请记住,在Android12 (API 31)中添加了对动态主题的支持,但并不是所有的制造商都支持它,更不用说低版本的兼容性实现了。
这里是关于如何使用动态颜色的一般文档,包括主题覆盖和活动颜色覆盖。
如果您想要创建主题视图,那么使用适当的DynamicColor主题或至少包装上下文来膨胀它们并让它们相应地进行样式化比较容易。
为了获得特定的颜色,您需要使用最后一步-用DynamicColors主题包装上下文:
if (DynamicColors.isDynamicColorAvailable()) {
// if your base context is already using Material3 theme you can omit R.style argument
Context dynamicColorContext = DynamicColors.wrapContextIfAvailable(context, R.style.ThemeOverlay_Material3_DynamicColors_DayNight);
// define attributes to resolve in an array
int[] attrsToResolve = {
R.attr.colorPrimary, // 0
R.attr.colorOnPrimary, // 1
R.attr.colorSecondary, // 2
R.attr.colorAccent // 3
};
// now resolve them
TypedArray ta = dynamicColorContext.obtainStyledAttributes(attrsToResolve);
int primary = ta.getColor(0, 0);
int onPrimary = ta.getColor(1, 0);
int secondary = ta.getColor(2, 0);
int accent = ta.getColor(3, 0);
ta.recycle(); // recycle TypedArray
// here you can consume dynamic colors
}https://stackoverflow.com/questions/71374425
复制相似问题