0

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?

M. Smith
  • 379
  • 1
  • 20

1 Answers1

1

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);
Doron Yakovlev Golani
  • 5,188
  • 9
  • 36
  • 60
  • Ah ok I see I was trying to trying to cast from a superclass to a subclass. So my question is still why is image.getDrawable() returning a BitmapDrawable when in the documentation it says it returns a Drawable? Or am I expecting to much granularity from the documentation since a BitmapDrawable is a Drawable? – M. Smith Nov 16 '16 at 22:02
  • The reason you are getting it is that the resource that was set in the ImageView is an image and was converted by the OS to a BitmapDrawable (if you chose a different resource, you could have received a different type of Drawable from your ImageView, for example ColorDrawable if the resource id was pointing to a color). – Doron Yakovlev Golani Nov 16 '16 at 22:06
  • @M.Smith BitmapDrawable is a Drawable, so it's a valid thing to return. This is how Java works. I'm not sure why you find this mysterious – Karakuri Nov 17 '16 at 01:30
  • @Karakuri lol I didn't know why/how it was returning as a BitmapDrawable. That was all – M. Smith Nov 17 '16 at 15:35