首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何以编程方式获得Material3主/重音颜色?

如何以编程方式获得Material3主/重音颜色?
EN

Stack Overflow用户
提问于 2022-03-06 21:37:57
回答 1查看 516关注 0票数 2

谷歌引入了材料3,允许用户选择一种颜色来申请整个系统主题,但他们的文档并不清楚,也没有提到如何通过编程获取当前的颜色,比如更改视图的背景色或文本颜色。

例如:view.setBackgroundColor(Material3.getPrimaryColor());

当然,Material3.getPrimaryColor()并不存在,它只是我所需要的一个例子。

任何帮助都是非常感谢的,谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-07 01:10:38

首先,请记住,在Android12 (API 31)中添加了对动态主题的支持,但并不是所有的制造商都支持它,更不用说低版本的兼容性实现了。

这里是关于如何使用动态颜色的一般文档,包括主题覆盖和活动颜色覆盖。

如果您想要创建主题视图,那么使用适当的DynamicColor主题或至少包装上下文来膨胀它们并让它们相应地进行样式化比较容易。

为了获得特定的颜色,您需要使用最后一步-用DynamicColors主题包装上下文:

代码语言:javascript
复制
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
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71374425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档