How can I get the primary color from my app theme?

Mayec picture Mayec · Feb 12, 2015 · Viewed 10.9k times · Source

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

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.

Is this possible?

Answer

ByteHamster picture ByteHamster · Feb 13, 2015

Use this:

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