layer-list drawable gets automatically converted to BitmapDrawable

158 views Asked by At

I have created a layer list drawable of 3 bitmap drawables in xml. When I try to retrieve that drawable in java code, I receive a BitmapDrawable object, not a LayerDrawable object.

Here is my layer-list drawable XML code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:width="24dp" android:height="24dp" android:id="@+id/a">
        <bitmap android:src="@drawable/add_to_list" />
    </item>
    <item android:width="24dp" android:height="24dp" android:id="@+id/b">
        <bitmap android:src="@drawable/refresh" />
    </item>
    <item android:width="24dp" android:height="24dp" android:id="@+id/c">
        <bitmap android:src="@drawable/trash" />
    </item>
</layer-list>

I declared an attribute named iconBar inside "Input_Field styleable xml" which should hold a reference to the above mentioned LayerDrawable and here is "Input_Field styleable xml":

   <resources>
  <declare-styleable name="InputField">
            <attr name="iconBar" format="reference" />          
        </declare-styleable>
    </resources>

Here is the xml code of the view InputField which has the attribute iconBar holding a reference to the layer-list drawable iconbar_drawable:

<com.example.asuss.calcuroid.CustomViews_ViewGroups.CustomViews.InputField
appx:iconBar="@drawable/iconbar_drawable"/>

My java code:

final TypedArray a = getContext().obtainStyledAttributes(
                    attrs, R.styleable.InputField, defStyle, 0); 
if(a.hasValue(R.styleable.InputField_IconsArray))
        {    
    LayerDrawable iconBar = (LayerDrawable) a.getDrawable(R.styleable.InputField_iconBar);

}

After running application, I am greeted with the following runtime exception

java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable cannot be cast to android.graphics.drawable.LayerDrawable

Could anyone please help me understand this weird behavior?

1

There are 1 answers

1
Ryan M On

The problem is that you are trying to inflate a styleable value as a drawable resource. The values in R.styleable aren't resource IDs, so you get whatever resource happened to get that ID.

To fix this, replace R.styleable.InputField_iconBar with R.drawable.your_xml_filename (and make sure you've imported your.package.name.R and not android.R).