作为参考(主题)以编程方式获取颜色值 [英] Get color value programmatically when it's a reference (theme)
本文介绍了作为参考(主题)以编程方式获取颜色值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑一下:
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屋!
查看全文