Android: how to use the current theme's colors in a drawable xml?
Asked Answered
O

1

36

I have defined two themes with different primary, primary dark, primary light and accent colors.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
</style>

<style name="AppTheme2" parent="AppTheme">
    <item name="colorPrimary">@color/primary_2</item>
    <item name="colorPrimaryDark">@color/primary_dark_2</item>
    <item name="colorAccent">@color/accent_2</item>
</style>

AppTheme is default for <application/> Then I set AppTheme2 in specific activities.

In a drawable file xml I'm using the same primary colors of AppTheme defined in colors.xml

The drawable is used in many activities from both themes, so when there is AppTheme2 I see the different colors. Is there a way to make the drawable use the colors of the current theme for the current activity?

Ovida answered 6/2, 2016 at 17:41 Comment(0)
K
85

You can use this attribute to get color from currently used theme:

android:color="?colorPrimary"

This is possible only for android 5.0 or higher.

Katowice answered 25/5, 2016 at 14:58 Comment(7)
is there anyway to do this in Android 4? or do i have to make this progrommatically?Entozoon
looks like it... developer.android.com/training/material/compatibility.htmlKatowice
sadly it doesn't work for my xamarin Project, after changing gradle i get weird exceptionsEntozoon
how to do this programmatically?Vidicon
@AnishKumar did you find any solution ?Sharisharia
How to do programmatically? I Tried this https://mcmap.net/q/357662/-how-can-i-get-the-primary-color-from-my-app-theme but it didn't workSharisharia
Note that it works for Android < 5.0 if it isn't used in drawable. In drawable it won't report any error in xml, but it will crash when you try to reference this drawable's xmlEspy

© 2022 - 2024 — McMap. All rights reserved.