Android Drawable Animation

Android Drawable Animation (also known by scene animation) is like an animated gif. It loads drawable resources one after another and shows it in order (declared in Drawable Animation) creating an animation.

Android Drawable Animation

You can define the images using a XML file that lists the drawable resources that composing the animation with a single <animation-list> element. The XML file needs belongs to the res/drawable/ directory of your Android project.

res/drawable/ball.xml

This tag has an important attribute named oneshot, it defines if this is a loop animation.

Now you need add the images you want animate in order and define the duration transaction time between the images

res/drawable/ball.xml

The Drawable Animation is recognized by Android as adrawable resource, you can use this in all places you could use a drawable, like an ImageView

res/layout/activity_main.xml

When you set a Drawable Animation as a source of an ImageView it will display the first item of your Drawable Animation. Is your responsability to start the animation.

MainActivity.java

In this case (because we defined the oneshot as true), the animation will run just once then stop and hold on the last frame. Unfortunately Drawable Animation has no reset method or something like that, so if you would like to play it again, you will need to stop the animation, rewind to the first scene and play it again.

MainActivity.java

Do not forget the importante AnimationDrawable.html#start() tip: AnimationDrawable.html#start() JavaDoc:

Do not call AnimationDrawable.html#start() in the Activity.onCreate(Bundle) method of your activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the Activity.onWindowFocusChanged(boolean) method in your activity, which will get called when Android brings your window into focus.

Take a look at the complete example app in https://github.com/danielpassos/android-animation-drawable

About the author

Daniel Passos

Open source addicted, geek, teacher, traveler, Android and iOS freak. Android Tech Leader at Red Hat and Dj in spare time

By Daniel Passos

Categories

Tags