Search code examples
androidandroid-resourcesandroid-theme

Get color value programmatically when it's a reference (theme)


Consider this:

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>

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!


Solution

  • This should do the job:

    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"
    

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

    setTheme(R.style.Theme_BlueTheme)
    

    in onCreate().

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