简体   繁体   中英

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

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?

Use this:

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

You can get your current primary (or primaryVariant, etc) color by using ?attr/colorPrimary as the color in XML.

For example, I have a SVG and I need to set the background same as my current primary color. So I can do this like:

<path
        android:fillColor="?attr/colorPrimary"
        android:pathData="M0,0h800v800h-800z" />

Even if you change the theme, the background color will automatically change as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM