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
}
1条答案
按热度按时间46scxncf1#
首先-请记住,Android 12(API 31)中添加了对动态主题的支持,但并非所有制造商都支持它,更不用说低版本的兼容性实现了。
这里是关于如何使用动态颜色的文档,包括主题覆盖和活动颜色覆盖。
如果你想创建主题化的视图,使用适当的
DynamicColor
主题或者至少 Package 上下文来填充它们并使它们相应地风格化会更容易。要获得特定的颜色,您需要使用最后一步-使用
DynamicColors
主题 Package 上下文:字符串