当它是参考(主题)时以编程方式获取颜色值 [英] Get color value programmatically when it's a reference (theme)

查看:23
本文介绍了当它是参考(主题)时以编程方式获取颜色值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

styles.xml

<style name="BlueTheme" parent="@android:style/Theme.Black.NoTitleBar">
    <item name="theme_color">@color/theme_color_blue</item>
</style>

attrs.xml

<attr name="theme_color" format="reference" />

color.xml

<color name="theme_color_blue">#ff0071d3</color>

所以主题颜色被主题引用.如何以编程方式获取 theme_color (参考)?通常我会使用 getResources().getColor() 但在这种情况下不会使用,因为它被引用了!

So the theme color is referenced by the theme. How can I get the theme_color (reference) programmatically? Normally I would use getResources().getColor() but not in this case because it's referenced!

推荐答案

这应该可以:

TypedValue typedValue = new TypedValue();
Theme theme = context.getTheme();
theme.resolveAttribute(R.attr.theme_color, typedValue, true);
@ColorInt int color = typedValue.data;

在调用此代码之前,还要确保将主题应用于您的活动.要么使用:

Also make sure to apply the theme to your Activity before calling this code. Either use:

android:theme="@style/Theme.BlueTheme"

在您的清单或调用中(在调用 setContentView(int) 之前):

in your manifest or call (before you call setContentView(int)):

setTheme(R.style.Theme_BlueTheme)

onCreate()中.

我已经用您的值对其进行了测试,并且效果很好.

I've tested it with your values and it worked perfectly.

这篇关于当它是参考(主题)时以编程方式获取颜色值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆