Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a theme attribute to android:startColor in gradient drawable in Android?

According to android documentation, android:startColor can take attributes as a value:

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

I am trying to add an attribute to my gradiant drawable, however I get an error. Here is the code for the drawable:

Here is the code in style.xml:

<style name="test" parent="android:Theme">
    <item name="android:startColor">#0b2749</item> 
    <item name="startColor">#0b2749</item>
</style>

When I try to run the activity I get this error message:

01-10 20:47:30.810: E/AndroidRuntime(7279): Caused by: java.lang.UnsupportedOperationException: Can't convert to color: type=0x2

I tried changing ?startColor to ?attr/startColor and still got the same error. I also applied the theme to the activity in the AndroidManifest.xml file.

How can I add a theme attribute to the gradient drawable?

like image 969
Kalimah Avatar asked Nov 05 '22 08:11

Kalimah


1 Answers

I was having the same problem in one of my drawable in which I want different colors based on the chosen theme. I found a workaround, that doesn't exactly solve the problem, but works for me. Instead of defining the color in my styles, I define the whole drawable as a reference.

In attrs.xml:

<resources>
    <attr name="myDrawable" format="reference"/>
<resources>

And in my style.xml:

<style name="style1">
    <item name="myDrawable">@drawable/myDrawable1</item>
<style>
<style name="style2">
    <item name="myDrawable">@drawable/myDrawable2</item>
<style>

Of course, you need to define two drawables in your drawable folder, myDrawable1 and myDrawable2, each one having the correct color hard-coded.

And it works fine.

like image 53
Guillaume Avatar answered Nov 12 '22 14:11

Guillaume