Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Theme drawable doesn't work with Color Drawable (Bug?)

So I'm trying to make a selector that uses a theme-based color as its background. Following the instructions from this SO answer, I first define my color drawable in res/values/colors.xml:

<color name="selected">#FFF7C9</color>

Then I define an attribute in res/values/attrs.xml:

<attr name="drawable_selected" format="reference" />

and then in my theme, I set attribute to my color drawable (res/values/styles.xml):

<style name="AppThemeWhite" parent="AppTheme">
    <item name="drawable_selected">@color/selected</item>
</style>

finally, I reference the attribute in my selector (res/drawable/selected_background):

<selector>
    <item android:state_activated="true" android:drawable="?drawable_selected" />
    <item android:drawable="@android:color/transparent" />
</selector>

When I run this, I get an error Binary XML file line #2: Error inflating class <unknown> when trying to inflate the class that uses the selector. However, when I change the selector's state_activated to reference the drawable directly using android:drawable="@color/selected", it works.

Is this a bug, or am I doing something wrong?

EDIT

If I add a color attribute (res/values/attrs.xml)

<attr name="selected_color" format="color" />

and define the color in my theme (res/values/styles.xml)

<item name="selected_color">#FFF7C9</item>

I can change the color drawable to change based on them (res/values/colors.xml)

<color name="selected">?selected_color</color>

and reference the drawable directly using android:drawable="@color/selected in my selector. However, this causes a crash as well! And changing the color drawable back to a hardcoded value of #FFF7C9 fixes it. It seems this whole theming system is pretty broken...

like image 614
woojoo666 Avatar asked Dec 08 '25 20:12

woojoo666


1 Answers

Reason

Yeah, referencing custom theme attributes from drawable (or colors) doesn't work on Android currently.

Here you can see more details about the issue that was reported long time ago: https://code.google.com/p/android/issues/detail?id=26251

As you can see they have finally resolved it in Android L release, but anywhere lower than L such referencing will fail.

Solution

To work around this issue you need to do something like that:

<selector>
    <item android:state_activated="true" android:drawable="@color/selected" />
    <item android:drawable="@android:color/transparent" />
</selector>

where @color/selected is defined as at the beginning of your post:

<color name="selected">#FFF7C9</color>
like image 185
Maciej Ciemięga Avatar answered Dec 10 '25 11:12

Maciej Ciemięga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!