Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

?attr in drawable resource causing Resources$NotFoundException

In a layer list I used solid in some items and set color using ?attr/text_color.

<stroke android:color="?attr/text_color" />

and set this drawable as background of a button. android:background="@drawable/myLayerListDrawable"

I was using this without any problem until I run this project on a lower api 18.

Caused by: android.content.res.Resources$NotFoundException: File res/drawable/myLayerListDrawable.xml from drawable resource ID #0x7f080063

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

Why is this happening and how this can be resolved !?

res\drawable\myLayerListDrawable.xml

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <selector>
        <item android:state_pressed="true">
            <shape android:shape="rectangle">
                <solid android:color="?attr/background_button_pressed" />
                <stroke
                    android:width="0.7dp"
                    android:color="?attr/text_color" />

                <corners android:radius="10dp" />

            </shape>
        </item>


        <item>
            <shape android:shape="rectangle">
                <solid android:color="@android:color/transparent" />
                <stroke
                    android:width="0.7dp"
                    android:color="?attr/text_color" />

                <corners android:radius="10dp" />

            </shape>
        </item>


    </selector>


</item>

------------------------------------------------------------------------------------------------------

Final Answer

We can't use ?attr in xml drawable resources pre api 21. Drawable resources created by aapt in compile time. Attr resources used for dynamic connection in runtime.

And the solution is to create different drawbles for every theme.

like image 731
Mehran Avatar asked Apr 06 '26 17:04

Mehran


1 Answers

You have to add a reference into your styles or attr file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <!-- Attributes must be lowercase as we want to use them for drawables -->
   <attr name="myColor" format="reference" />
</resources>

and add this to your theme:

<item name="myColor">#c3c3c3</item>
like image 53
John Doe Avatar answered Apr 09 '26 08:04

John Doe