2

i am using AppCompat 22.1.1.

For some reasons, my app can change its theme on the fly, during the user navigation. (i.e. move to an another part of the app, like in the google play store app, when you're moved from the "my apps" part, to the "movie" part for example)

To avoid creating one drawable background per theme, i tried to create a background like this :

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="?attr/colorPrimary" /></shape>

When changing the theme programmatically, i suppose the colorPrimary will change too, and a button inflated after that, will be tinted with the colour of the new theme.

But i have an inflate exception on pre-lollipop (but works on lollipop). The drawable cannot find the attribute attr/colorPrimary, why ?

Here is the simple theme.xml i'm using :

 <style name="MyTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/my_blue</item>
    <item name="colorPrimaryDark">@color/my_blue_dark</item>
    <item name="colorAccent">@color/my_blue_light</item>
</style>

The colors are in values/colors.xml, just hexa colors.. And all resources are in the "values" dir, and NOT in values-r21 dir.

Sakaroz
  • 85
  • 1
  • 7

2 Answers2

3

Create a color_primary.xml color resource in res/color/:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="?attr/colorPrimary"/>
</selector>

Then reference this in your drawable:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
   <solid android:color="@color/color_primary" />
</shape>
  • 1
    Nice idea, sounds like an acceptable workaround but unfortunately, similar to the shape non-attr-support, this doesn't seem to work pre-Marshmallow. Everything is red. https://code.google.com/p/android/issues/detail?id=78554 – NeilS Aug 22 '16 at 16:40
1

From my experience, I don't know, but I'm pretty sure there's nothing you can do via XML. Lots of framework resources are provided twice, in the form some_drawable_dark.xml and some_drawable_light.xml; it looks like you can't reference theme values from drawable and color folders.

So you should either:

  • Create x static resources, where x is the number of themes you are putting in;
  • Operate at runtime, using setColorFilter() and such. Depending on the case, it can be hard.
natario
  • 24,954
  • 17
  • 88
  • 158
  • 1
    The stack trace : Caused by: java.lang.UnsupportedOperationException: Can't convert to color: type=0x2. Yep it seems i must handle it programmatically, maybe the new AppCompatWidgets and their new colortint utility methods – Sakaroz Apr 28 '15 at 15:56