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?
The problem is that you are trying to inflate a
styleable
value as adrawable
resource. The values inR.styleable
aren't resource IDs, so you get whatever resource happened to get that ID.To fix this, replace
R.styleable.InputField_iconBar
withR.drawable.your_xml_filename
(and make sure you've importedyour.package.name.R
and notandroid.R
).