android 如何以编程方式获取Material 3原色/强调色?

h7appiyu  于 2023-08-01  发布在  Android
关注(0)|答案(1)|浏览(161)

Google推出了Material 3,允许用户选择一种颜色来应用于整个系统主题,但他们的文档并不清楚,也没有提到如何以编程方式获取当前颜色以用于应用程序,例如更改视图的背景色或文本颜色。
例如:view.setBackgroundColor(Material3.getPrimaryColor());
当然,Material3.getPrimaryColor()并不存在,它只是我需要的一个例子。
任何帮助都很感激,谢谢。

46scxncf

46scxncf1#

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

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
}

字符串

相关问题