我如何从我的应用程序主题获得主颜色?

时间:2022-11-20 21:15:24

In my Android java code, how can I reference the color "colorPrimary" set in my theme?

在我的Android java代码中,如何引用主题中的颜色“colorPrimary”集?

I have the following theme definition:

我有以下主题定义:

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">

    <item name="colorPrimary">@color/myColor1</item>
    <item name="colorPrimaryDark">@color/myColor2</item>      
    <item name="colorControlNormal">@color/myColor3</item>
    <item name="colorControlActivated">@color/myColor4</item>

</style>

I could reference the color resource directly (R.color.myColor1), but I would prefer to reference the theme's primaryColor setting, so that it stays consistent if the colorPrimary changes in the future.

我可以直接引用颜色资源(R.color.myColor1),但我更愿意引用主题的主色调设置,以便在以后的colorPrimary更改时保持一致。

Is this possible?

这是可能的吗?

1 个解决方案

#1


27  

Use this:

用这个:

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
int color = typedValue.data;

#1


27  

Use this:

用这个:

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
int color = typedValue.data;