Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference colour attribute in drawable? [duplicate]

I would like to do a simple thing: Define a drawable which has exacly same background colour as system state-pressed background colour. I do it like this in res/drawables/my_drawable.xml:

<?xml version="1.0" encoding="utf-8"?>   <selector xmlns:android="http://schemas.android.com/apk/res/android" >     <item android:state_selected="true">       <color android:color="?android:attr/colorPressedHighlight"/>     </item>     <item android:state_selected="false">       <color android:color="@color/section_list_background"/>     </item>       </selector> 

I always get:

java.lang.UnsupportedOperationException: Cant convert to color: type=0x2 

Any clues?

Regards

like image 201
Michal Avatar asked Jun 12 '12 09:06

Michal


People also ask

How do I change the color of a drawable in xml?

Use app:drawableTint="@color/yourColor" in the xml instade android:drawableTint="@color/yourColor" . It has the backward compatibility.

How do you cite Drawables in Android?

Note: A color resource can also be used as a drawable in XML. For example, when creating a state list drawable, you can reference a color resource for the android:drawable attribute ( android:drawable="@color/green" ).


1 Answers

You might need to do the following to fix your problem:

1) Define 2 colors for each theme in your colors file:

<?xml version="1.0" encoding="utf-8"?> <resources>     <color name="my_color_dark">#ff33B5E5</color>     <color name="my_color_light">#ff355689</color> </resources> 

2) Create file res/values/attrs.xml with contents:

<?xml version="1.0" encoding="utf-8"?> <resources>     <attr name="my_color" format="reference" /> </resources> 

3) Assuming you have 2 themes in your styles.xml (Theme.dark and Theme.light) define:

<style name="Theme.dark" parent="@style/Theme.Sherlock">     <item name="my_color">@color/my_color_dark</item> </style>  <style name="Theme.light" parent="@style/Theme.Sherlock.Light">     <item name="my_color">@color/my_color_light</item> </style> 

4) Use the color in a drawable:

<color android:color="?attr/my_color"/> 

Hope this should fix your problem.

like image 69
petrsyn Avatar answered Sep 28 '22 02:09

petrsyn