Android: AnimationDrawable cast error

TheOneX picture TheOneX · Jan 14, 2015 · Viewed 13.6k times · Source

I was following the Google provided example of how to use AnimationDrawable with an ImageView. You can find it here: http://developer.android.com/guide/topics/graphics/drawable-animation.html

imageView.setBackgroundResource(R.drawable.animation);
AnimationDrawable animation = (AnimationDrawable)imageView.getBackground();
animation.start();

When I run it I get the error:

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

Google seems to think this should work, but if you cannot cast a BitmapDrawable to AnimationDrawable I am not sure how this is supposed to work?

Answer

TheOneX picture TheOneX · Jan 15, 2015

I figured out the solution to this problem.

imageView.setImageDrawable(getResources().getDrawable(R.drawable.animation));
AnimationDrawable animation = (AnimationDrawable) imageView.getDrawable();
animation.start();

I have no idea why Google's documentation says to use the background, but using setImageDrawable and getDrawable works. Honestly it makes more sense it would work this way than the other way anyways.