androidcastingimageviewclasscastexceptionanimationdrawable

How to detect if an Android ImageView drawable is an anim?


In my app I have an ImageView that can have a changing source. The source is always a Drawable, either a Bitmap or an xml anim made of drawables. But, when the source is an animation, I have to call the start() method on the Drawable and thus cast it to an AnimationDrawable first.

Of course, the non animated Drawable cast to AnimationDrawable throws a ClassCastException. I currently catch it and it works pretty well. But I'm not satisfied with this and I would prefer not to try to cast the Drawable if it's not an animation.

Is there a way to detect the type of Drawable used as source of an ImageView so I could cast it only if it's an animation ?

Thanks, Nicolas.


Solution

  • instanceof works fine, thanks !

    My working code :

    Drawable drawable = imageView.getDrawable();
    if(drawable instanceof AnimationDrawable){
        ((AnimationDrawable) drawable).start();
    }