Skip to main content

AnimationDrawable and AnimatedVectorDrawable Examples

AnimatedVectorDrawable is an essential part of the Android platform. It is used to create complex animations for the Android platform. The AnimatedVectorDrawable is a drawable that can be used as an image source for various views in your Android app. In this article, we will learn how to create an AnimatedVectorDrawable in Android step by step.

Requirements

Before we start creating an AnimatedVectorDrawable, we need to have the following requirements:

  • Android Studio 3.0 or above
  • Android SDK 21 or above

Steps to Create an AnimatedVectorDrawable

Step 1: Create a New Android Project

Open Android Studio and create a new Android project. Choose a blank activity as a template and give your app a name.

Step 2: Create a Vector Drawable

In this step, we will create a vector drawable. A vector drawable is a scalable image format that can be used to create icons, logos, and other graphics that can be scaled up or down without losing their quality.

To create a vector drawable, right-click on the res folder of your project and select New > Vector Asset. In the Vector Asset Studio window, select the Clip Art option and choose an icon of your choice. You can also choose the color and size of the icon.

Step 3: Create an AnimatedVectorDrawable

In this step, we will create an AnimatedVectorDrawable.

Create a new drawable file in the res/drawable folder and name it animated_vector.xml. In this file, we will define the AnimatedVectorDrawable.

<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/vector_drawable">
<target
android:name="path"
android:animation="@animator/path_morph" />
</animated-vector>

In the above code, we define an AnimatedVectorDrawable and set the vector_drawable as its drawable source. We also define a target that specifies the path element of the vector_drawable and the path_morph animator.

Step 4: Create an Animator

In this step, we will create an animator that will animate the path element of the vector_drawable.

Create a new animator file in the res/animator folder and name it path_morph.xml. In this file, we will define the animator that will morph the path element.

<objectAnimator
android:duration="1000"
android:propertyName="pathData"
android:valueFrom="@string/path1"
android:valueTo="@string/path2"
android:valueType="pathType" />

In the above code, we define an objectAnimator that will animate the pathData property of the path element. We specify the duration of the animation and the valueFrom and valueTo attributes that define the starting and ending paths of the animation.

Step 5: Use the AnimatedVectorDrawable

In this step, we will use the AnimatedVectorDrawable in our app.

Open the layout file of your activity and add an ImageView element. Set the src attribute of the ImageView to the animated_vector drawable.

<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/animated_vector" />

Step 6: Start the Animation

In this step, we will start the animation of the AnimatedVectorDrawable.

In your activity class, get a reference to the ImageView and call the setImageDrawable() method to set the AnimatedVectorDrawable as the drawable source of the ImageView. Then, get a reference to the AnimatedVectorDrawable and call the start() method to start the animation.

val imageView = findViewById<ImageView>(R.id.image_view)
imageView.setImageResource(R.drawable.animated_vector)

val animatedVectorDrawable = imageView.drawable as AnimatedVectorDrawable
animatedVectorDrawable.start()

Step 7: Run the App

In this step, we will run the app to see the animation.

Run the app on an emulator or a physical device. The animation should start automatically and morph the path element of the vector_drawable.

Examples

This section will teach you about the AnimationDrawable and AnimatedVectorDrawable class via simple examples.

Example 1: Kotlin Android AnimatedVectorDrawble Example

In the first example you will learn about AnimatedVectorDrawable. Here is the demo screenshot:

Kotlin Android AnimatedVectorDrawable Example

What is a VectorDrawable?

It is a class that lets you create a drawable based on an XML vector graphic.

What is AnimatedVectorDrawable?

This class animates properties of a VectorDrawable with animations defined using ObjectAnimator or AnimatorSet.

Starting from API 25, AnimatedVectorDrawable runs on RenderThread (as opposed to on UI thread for earlier APIs). This means animations in AnimatedVectorDrawable can remain smooth even when there is heavy workload on the UI thread. Note: If the UI thread is unresponsive, RenderThread may continue animating until the UI thread is capable of pushing another frame. Therefore, it is not possible to precisely coordinate a RenderThread-enabled AnimatedVectorDrawable with UI thread animations. Additionally, Animatable2.AnimationCallback.onAnimationEnd(Drawable) will be called the frame after the AnimatedVectorDrawable finishes on the RenderThread.

AnimatedVectorDrawable can be defined in either three separate XML files, or one XML.

You can read more here

Step 1: Create Project

Start by creating an empty Android Studio project.

Step 2: Dependencies

No external dependency is needed.

Step : Write Code

Go to the MainActivity.kt and add the following imports including the android.graphics.drawable.Animatable:

import android.graphics.drawable.Animatable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

Extend the AppCompatActivity:

class MainActivity : AppCompatActivity() {

Declare the Animatable as a property:

    private lateinit var animatable: Animatable

Then initialize the Animatable inside the onCreate():

    override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
animatable = animatedImageView.drawable as Animatable
}

When the startButton is clicked we will start the animation using the start() function:

    override fun onStart() {
super.onStart()
startButton.setOnClickListener {
animatable.start()
}
}
}

Here is the full code:

MainActivity.kt

import android.graphics.drawable.Animatable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

private lateinit var animatable: Animatable

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
animatable = animatedImageView.drawable as Animatable
}

override fun onStart() {
super.onStart()
startButton.setOnClickListener {
animatable.start()
}
}
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

NumberLink
1.Download Example
2.Follow code author
3.Code: Apache 2.0 License

Let us look at the second example.

Example 2: AnimationDrawable

What is AnimationDrawable

It is an object used to create frame-by-frame animations, defined by a series of Drawable objects, which can be used as a View object's background.

The simplest way to create a frame-by-frame animation is to define the animation in an XML file, placed in the res/drawable/ folder, and set it as the background to a View object. Then, call start() to run the animation.

An AnimationDrawable defined in XML consists of a single element and a series of nested tags. Each item defines a frame of the animation.

For example here is how you would create the animation in xml:

 <!-- Animation frames are wheel0.png through wheel5.png
files inside the res/drawable/ folder -->
<animation-list android:id="@+id/selected" android:oneshot="false">
<item android:drawable="@drawable/wheel0" android:duration="50" />
<item android:drawable="@drawable/wheel1" android:duration="50" />
<item android:drawable="@drawable/wheel2" android:duration="50" />
<item android:drawable="@drawable/wheel3" android:duration="50" />
<item android:drawable="@drawable/wheel4" android:duration="50" />
<item android:drawable="@drawable/wheel5" android:duration="50" />
</animation-list>

Then to load and play the animation you can use the following code:

 // Load the ImageView that will host the animation and
// set its background to our AnimationDrawable XML resource.
ImageView img = (ImageView)findViewById(R.id.spinning_wheel_image);
img.setBackgroundResource(R.drawable.spin_animation);

// Get the background, which has been compiled to an AnimationDrawable object.
AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

// Start the animation (looped playback by default).
frameAnimation.start();

You can read more about this class here.

Let us now look at isolated examples.

Step 1: Create Project

Start by creating an empty Android Studio project.

Step 2: Dependencies

Add ConstraintLayout as a dependency in your app/build.gradle.

Step 3: Design Layout

Go to your activity_main.xml and create a TextView inside a constraintLayout:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/drawable_gradient_animation_list"
tools:context=".MainActivity"
>
<!-- Your layout here -->
<TextView
android:layout_width="368dp"
android:layout_height="520dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="@string/app_name"
android:textAlignment="center"
android:textColor="@android:color/background_light"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="@string/app_name"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

Step : Write Code

Go to MainActivity.java and add the following code:

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.app.AppCompatActivity;

Extend the AppCompatActivity:

public class MainActivity extends AppCompatActivity {

Declare a ConstraintLayout and AnimationDrawable objects:

  private ConstraintLayout constraintLayout;
private AnimationDrawable animationDrawable;

Override the onCreate():

  @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Hide the actionBar:

    getSupportActionBar().hide();

Reference the ConstraintLayout:

    // init constraintLayout
constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);

Initialize the animation drawable by getting background from constraint layout:

    animationDrawable = (AnimationDrawable) constraintLayout.getBackground();

Set the enter fade animation duration to 5 seconds on the AnimationDrawable:

    animationDrawable.setEnterFadeDuration(5000);

Then set the exit fade animation duration to 2 seconds:

    animationDrawable.setExitFadeDuration(2000);
}

Override our onResume() method:

  @Override
protected void onResume() {
super.onResume();

Check that the AnimationDrawable is not null and it is not running, then start the animation:

    if (animationDrawable != null && !animationDrawable.isRunning()) {
// start the animation
animationDrawable.start();
}
}

In the onPause() stop the animationDrawable:

  @Override
protected void onPause() {
super.onPause();
if (animationDrawable != null && animationDrawable.isRunning()) {
// stop the animation
animationDrawable.stop();
}
}
}

Here is the full code:

MainActivity.java

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
private ConstraintLayout constraintLayout;
private AnimationDrawable animationDrawable;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

getSupportActionBar().hide();

// init constraintLayout
constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);

// initializing animation drawable by getting background from constraint layout
animationDrawable = (AnimationDrawable) constraintLayout.getBackground();

// setting enter fade animation duration to 5 seconds
animationDrawable.setEnterFadeDuration(5000);

// setting exit fade animation duration to 2 seconds
animationDrawable.setExitFadeDuration(2000);
}

@Override
protected void onResume() {
super.onResume();
if (animationDrawable != null && !animationDrawable.isRunning()) {
// start the animation
animationDrawable.start();
}
}

@Override
protected void onPause() {
super.onPause();
if (animationDrawable != null && animationDrawable.isRunning()) {
// stop the animation
animationDrawable.stop();
}
}
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

NumberLink
1.Download Example
2.Follow code author
3.Code: Apache 2.0 License

Conclusion

In this article, we learned how to create an AnimatedVectorDrawable in Android step by step. We also learned how to use the AnimatedVectorDrawable in an app and start its animation. The AnimatedVectorDrawable is a powerful tool for creating complex animations in Android, and it can be used to create various types of animations, such as morphing, rotation, and scaling.