java.lang.UnsupportedOperationException: Can't convert to color: type=0x2

Such an error falls out when testing for API <21 (i.e., everything falls, although everything works on 5+ versions of the android). Plus AndroidStudio displays a warning in the xml-drawable , but does not issue any prompts. What is the trouble - who is to blame and what to do?

Here is xml drawable :

 <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:angle="90" android:endColor="?colorPrimary" android:startColor="@android:color/transparent"/> </shape> 
  • The question is a personal problem; The answer is a free translation of the solution from en-SO ; - Yuriy SPb

1 answer 1

According to en-SO, the problem is that before API 21 you cannot use color-reference attributes in xml-drawable , only the color references from @color . In this case, convert the file as follows:

 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:angle="90" android:endColor="@color/my_awesome_color_that_i_use_as_color_primary_in_my_awesome_theme" android:startColor="@android:color/transparent"/> </shape> 

If, like me, you need to use the same xml-drawable but with different colors for different themes, then nothing remains except:

  1. Create an attribute link to xml-drawable

     <?xml version="1.0" encoding="utf-8"?> <resources> <!-- по ссылке утверждают, что надо обязательно только lowerCase пользовать в названии --> <attr name="my_drawable" format="reference" /> </resources> 
  2. Assign a link to a separate xml-drawable in this attribute for each topic.

     <style name="MyTheme" parent="@android:style/Theme.NoTitleBar"> <item name="my_drawable">@drawable/my_drawable_for_this_theme</item> </style> 
  3. use this attribute where appropriate. for example a textView background

     <TextView android:background="?my_drawable" /> 
  4. Of course, don't forget to create one xml-drawable with a specific color for each theme.