Hello, in this video, I’ll show you how to use the AnimationDrawable class to create animations through a sequence of images in Android.
Hello, in this video, I’ll show you how to use the AnimationDrawable class to create animations through a sequence of images in Android.
How it works:
The process for this is simple; we just have to divide our animations into separate images, pass them into an AnimationDrawable object, and it’ll display each one sequentially one after another creating an illusion that it is moving.
Getting started
To begin, place all the individual images for your animation in the drawable folder. Make sure each image is a separate frame for the animation.
If you do not have any images at the moment, you can download the sample images provided here.
Create a new Drawable resource file by right clicking on the drawable folder.
Give the file a name and change the Root element to animation-list.
For each image of the animation, add an item element and specify the duration of how long the image will be displayed in milliseconds.
Playing the animation
Once the animation file is created, we can add the animation to a view.
In the layout file for your activity, add a ImageView and select the animation resource file you have created.
In the activity file, create a reference to the ImageView.
To start the animation, override the onStart() method. Grab the animation drawable object and call start().
The start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window.
If we run the app, the animation will play.
Playing the animation on other Views
For views that does not have the getDrawable() method, we should use getBackground() instead.
bounceAnimation = (AnimationDrawable) someView.getBackground();
Then in the layout file, set the background to the animation drawable.
Useful Settings
To stop the animation from repeating, set the oneShot attribute to true in the animation drawable xml.
To restart the animation from the beginning, call the stop() method from the AnimationDrawable object.
bounceAnimation.stop();