M. Smith M. Smith - 24 days ago 6
Android Question

Android: cannot cast BitmapDrawable to a ClipDrawable

I'm trying to implement a simple ClipDrawable using Android Jellybean (SDK 18). I don't understand why I'm getting the casting error for ImageView.getDrawable() when that returns a Drawable, not a BitmapDrawable

Here's my relevant code in the onCreate() of an activity:

ImageView image = (ImageView) findViewById(R.id.guage_one);
ClipDrawable drawable = (ClipDrawable) image.getDrawable();
drawable.setLevel(10000);


Why would I get a ClassCastException for this? I know BitmapDrawable and ClipDrawable are subclasses of Drawable so you can't cast them to one another, I know that. But why is image.getDrawable() returning a BitmapDrawable and not just a drawable? Am I missing something in the documentation?

Answer

ClipDrawable does not inherit BitmapDrawable.

This is it's inheritance tree:

java.lang.Object

↳ android.graphics.drawable.Drawable

↳ android.graphics.drawable.DrawableWrapper

↳ android.graphics.drawable.ClipDrawable

To convert a BitmapDrawable to ClipDrawable you can do the following:

ImageView image = (ImageView) findViewById(R.id.guage_one);
ClipDrawable clipDrawable = new ClipDrawable(image.getDrawable(), Gravity.LEFT, ClipDrawable.HORIZONTAL);