如何以编程方式获取 Material3 primary/accent 颜色?
How to get Material3 primary/accent colors programmatically?
Google引入了Material3,允许用户选择一种颜色应用到整个系统主题,但是他们的文档不清楚,也没有提到如何获得当前颜色以编程方式用于应用程序,例如更改视图的背景颜色或文本颜色。
例如:view.setBackgroundColor(Material3.getPrimaryColor());
当然Material3.getPrimaryColor()
不存在,这只是我需要的一个例子。
感谢任何帮助,谢谢。
首先 - 请记住,在 Android 12 (API 31) 中添加了对动态主题的支持,但并非所有制造商都支持它,很多less 低版本的兼容性实现。
这里是关于如何 use dynamic colors 的一般文档,包括主题叠加和 activity 颜色叠加。
如果您想创建主题视图,使用适当的 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
}
Google引入了Material3,允许用户选择一种颜色应用到整个系统主题,但是他们的文档不清楚,也没有提到如何获得当前颜色以编程方式用于应用程序,例如更改视图的背景颜色或文本颜色。
例如:view.setBackgroundColor(Material3.getPrimaryColor());
当然Material3.getPrimaryColor()
不存在,这只是我需要的一个例子。
感谢任何帮助,谢谢。
首先 - 请记住,在 Android 12 (API 31) 中添加了对动态主题的支持,但并非所有制造商都支持它,很多less 低版本的兼容性实现。
这里是关于如何 use dynamic colors 的一般文档,包括主题叠加和 activity 颜色叠加。
如果您想创建主题视图,使用适当的 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
}