Search code examples
androidmaterial-designandroid-styles

Wrong colorAccent when retrieving from theme


I want to use colorAccent from application theme. There are two themes with different accent colors. I am implement it with this code:

Styles:

<style name="BaseAppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>

<style name="AppGreenTheme" parent="BaseAppTheme">
    <item name="colorAccent">@color/green</item>
</style>

<style name="AppRedTheme" parent="BaseAppTheme">
    <item name="colorAccent">@color/red</item>
</style>

Layout:

<FrameLayout
    android:id="@+id/receives_funds_share"
    android:background="?colorAccent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

But it shows wrong color (#04dac6). When the correct color is darker (#05c0a5).

When I changed it from android:background="?colorAccent" to android:background="@color/green" it works well. What it the difference? How to correctly retrieve accentColor from style?

Tested on Android 11.


Solution

  • The thing is, since you are using Theme.MaterialComponents.Light.DarkActionBar as your parent, colorAccent does not apply. Instead try replacing it with colorSecondary as follows.

    The Theme.MaterialComponents uses the colorSecondary and is so described in their docs. All the components defined in the library uses this attribute.

    <style name="BaseAppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    </style>
    
    <style name="AppGreenTheme" parent="BaseAppTheme">
        <item name="colorSecondary">@color/green</item>
    </style>
    
    <style name="AppRedTheme" parent="BaseAppTheme">
        <item name="colorSecondary">@color/red</item>
    </style>