Android Animation tutorial with examples

Android Animation tutorial Android Animation is used to give the UI a rich look and feel. It is the process of creating motion and shape change. Animations in android apps can be performed through XML or android code.

Android 2.3 and prior releases support three types of animation: frame-by-frame animation, which occurs when a series of frames is drawn one after the other at regular intervals; layout animation, where you animate the layout of the views inside a container such as lists and tables; and view animation, in which any view can be animated. In layout animation the focus is not any given view but the way views come together to form the composite layout. Android 3.0 enhanced animation by extending it to any Java property including the properties of UI elements.

Frame-by-Frame animation

Frame-by-frame animation is where a series of images are shown in succession at quick intervals so that the final effect is that of an object moving or changing.

In Android, frame-by-frame animation is implemented through the class AnimationDrawable. This class is a Drawable. These objects are commonly used as backgrounds for views. AnimationDrawable, in addition to being a Drawable, can take a list of other Drawable resources (like images) and render them at specified intervals.

To use this AnimationDrawable class, start with a set of Drawable resources (for example, a set of images) placed in the /res/drawable subdirectory. You will then construct an XML file that defines the AnimationDrawable using a list of these images. This XML file needs to be placed in the /res/drawable/frame_animation.xml subdirectory as well.

        android:duration="50" />

        android:duration="50" />

        android:duration="50" />

Each frame points to one of the images you have assembled through their resource IDs. The animation-list tag gets converted into an AnimationDrawable object representing the collection of images. You then need to set this AnimationDrawable as a background resource for our ImageView control in the activity layout. Assuming that the file name for this XML file is frame_animation.xml and that it resides in the /res/drawable subdirectory, you can use the following code to set the AnimationDrawable as the background of the ImageView:


With this code, Android realizes that the resource ID R.drawable.frame_animation is an XML resource and accordingly constructs a suitable AnimationDrawable Java object for it before setting it as the background. Once this is set, you can access this AnimationDrawable object by doing a get on the view object like this:

Object backgroundObject = view.getBackground();
AnimationDrawable ad = (AnimationDrawable) backgroundObject;

Once you have the AnimationDrawable object, you can use its start() and stop() methods to start and stop the animation.

You can create moving gradient animation via AnimationDrawable.

View animation

View Animation can be applied on a single view only and, at the end of the animation, the effects are lost.

Through view animation you can animate a view by manipulating its transformation matrix. A transformation matrix is like a lens that projects a view on to the display. A transformation matrix can affect the projected views scale, size, position, and color. Identity transformation matrix preserves the original view. You start with an identity matrix and apply a series of mathematical transformations involving size, position, and orientation. You then set the final matrix as the transformation matrix for the view you want to transform.

Android exposes the transformation matrix for a view by allowing registration of an animation object with that view. The animation object will be passed to the transformation matrix.

View animations are further categorized into tween animation and frame animation.

Tween animations are useful when you want to perform one or more transformations to a single view. The available transformations are rotation, scaling, translation, and fading.

Tween animation uses a different approach that creates an animation by performing a series of transformations on a single View. In Android, it provides access to the following classes that are the basis for all the animations:

  • AlphaAnimation controls transparency changes.
  • RotateAnimation controls rotations.
  • ScaleAnimation controls growing or shrinking.
  • TranslateAnimation controls position changes.

These four animation classes can be used for transitions between activities, layouts, views, and so on. All these can be defined in the layout XML file as <alpha>, <rotate>, <scale> and <translate>. They all have to be contained within an AnimationSet <set>:

  • <alpha> attributes: android:fromAlpha, android:toAlpha. The alpha value translates the opacity from 0.0 (transparent) to 1.0 (opaque).
  • <rotate> attributes: android:fromDegrees, android:toDegrees, android:pivotX, android:pivotY. The rotate specifies the angle to rotate an animation around a center of rotation defined as the pivot.
  • <scale> attributes: android:fromXScale, android:toXScale, android:fromYScale, android:toYScale, android:pivotX, android:pivotY. The scale specifies how to change the size of a view in the x axis or y axis. The pivot location that stays fixed under the scaling can also be specified.
  • <translate> attributes: android:fromXDelta, android:toXDelta, android:fromYDelta, android:toYDelta. The translate specifies the amount of translation to perform on a view.

For each animation effect, there are properties such as animation start time, duration, and whether the animation is a sequential or simultaneous animation.

The simplest way apply the animation to view is

Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);

Next, we create a resource directory under the res folder names anim to keep all the xml files containing the animation logic.

  1. Right click on the res folder.
  2. Select New / Android resource file.
  3. Write sample_animation as the name of the file
  4. Choose the Animation resource type. The directory name field will change to anim.

Following is a sample_animation.xml xml file showing an android animation code logic.

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"

Let's examine properties

  • android:interpolator. It is the rate of change in animation. We can define our own interpolators using the time as the constraint. In the above xml code an inbuilt interpolator is assigned.
  • android:duration. Duration of the animation in which the animation should complete. It is 300ms here. This is generally the ideal duration to show the transition on the screen.
An interpolator is a mathematical tool that takes original time instances as an input, performs operation based on its mathematical equation and provides output as a time instance of a replacement frame for that given input instance.

The start and end of the animation are set using:

  • TRANSFORMATION is the transformation that we want to specify. In our case we start with an x and y scale of 0 and end with an x and y scale of 1.
  • android:fillAfter property specifies whether the view should be visible or hidden at the end of the animation. We’ve set it visible in the above code. If it sets to false, the element changes to its previous state after the animation.
  • android:startOffset. It is the waiting time before an animation starts. This property is mainly used to perform multiple animations in a sequential manner.
  • android:repeatMode. This is useful when you want the animation to be repeat.
  • android:repeatCount. This defines number of repetitions on animation. If we set this value to infinite then animation will repeat infinite times.

Our aim is to show an animation when any widget (lets say Button) is clicked. For that we need to use the Animation Class. The xml file that contains the animation logic is loaded using AnimationUtils class by calling the loadAnimation() function. The below snippet shows this implementation.

Animation animation;
animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.sample_animation);

This Animation class has many useful functions which are listed below

  • Method start() starts the animation.
  • Method setDuration(long duration) sets the duration of an animation.
  • Method getDuration() gets the duration which is set by above method.
  • Method end() ends the animation.
  • Method cancel() cancels the animation.

To start the animation we need to call the startAnimation() function on the UI element as shown in the snippet below:


Here we perform the animation on a TextView component by passing the type of Animation as the parameter.

Ripple effect

Let's decorate Button with ripple effect. The RippleDrawable was added in API 21, so it's not available on earlier SDKs. You can move your drawable file to res/drawable-v21/ripple_effect.xml to ensure it doesn't crash on earlier releases.

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#f816a463" />

Create res/drawable/ripple_effect.xml for devices with API 20 and below.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#f816a463" />
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <stroke android:color="#f816a463" />
    <item android:drawable="@color/button_ripple" />


<color name="button_ripple">#E8EAF6</color>

And set background of button to above drawable resource file. Final code of xml layout activity looks like this.

    android:text="Start animation" />

Transition animation

Here is a simple snippet how to make transition animation between two Drawable.

Create res/drawable/transition.xml

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/position_on" />
    <item android:drawable="@drawable/position_off" />

Add ImageView to your layout:

    android:src="@drawable/transition" />

Add code to your controller

ImageView ivPosition = (ImageView) findViewById(R.id.ivPosition);
TransitionDrawable drawable = (TransitionDrawable) ivPosition.getDrawable();

Also we can create TransitionDrawable in code.

Drawable backgrounds[] = new Drawable[2];
backgrounds[0] = getResources().getDrawable(R.drawable.position_on);
backgrounds[1] = getResources().getDrawable(R.drawable.position_off);

TransitionDrawable crossfader = new TransitionDrawable(backgrounds);

ImageView ivPosition = (ImageView) findViewById(R.id.ivPosition);


Then if you want to transition back to the original image you can call

// make sure the transition occurred

// reverse transition

Animations snippets

Following is a list of animations snippets for most of the common android animations.

Fade In Animation.

File fade_in.xml in res/anim.

<set xmlns:android="http://schemas.android.com/apk/res/android"

        android:toAlpha="1.0" />

Here Alpha references the opacity of an object. An object with lower Alpha values is more transparent, while an object with higher Alpha values is less transparent, more opaque. Fade in animation is nothing but increasing Alpha value from 0 to 1.

Fade Out Animation.

File fade_out.xml in res/anim.

<set xmlns:android="http://schemas.android.com/apk/res/android"

        android:toAlpha="0.0" />

Fade out android animation is exactly opposite to fade in, where we need to decrease the Alpha value from 1 to 0.

Rotate Animation.

File rotate.xml in res/anim.

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="0"

A from/toDegrees tag is used here to specify the degrees and a cyclic interpolator is used.

Move Animation.

File move.xml in res/anim.


        android:duration="800" />

Slide Up Animation.

File slide_up.xml in res/anim.

<set xmlns:android="http://schemas.android.com/apk/res/android"

        android:toYScale="0.0" />

It’s achieved by setting android:fromYScale="1.0″ and android:toYScale="0.0″ inside the scale tag.

Slide Down Animation.

File slide_down.xml in res/anim.

<set xmlns:android="http://schemas.android.com/apk/res/android"

        android:toYScale="1.0" />

This is just the opposite of slide_up.xml.


If you want apply animation just in few statements than you should use AndroidViewAnimations. It's a collection of different view animations splited in Attension, Special, Bounce, Fade, Flip, Rotate, Slide, Zoom groups.

To compile the AndroidViewAnimations library, we need to add the library in the app's dependencies. Open the app's build.gradle file. Add the project in the dependencies. It will compile the library at run time.

dependencies {
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.easing:library:1.0.1@aar'
    compile 'com.daimajia.androidanimations:library:1.1.3@aar'

We will call the with(), duration() and playOn() method of YoYo class. These method used to make the animation on your view.


Layout animation

LayoutAnimation is used to animate the views in an Android layout. You can use this type of animation for example with common layout controls like ListView and GridView. Unlike frame-by-frame animation, layout animation is not achieved through repeating frames but by changing the transformation matrix of a view. Every view in Android has a transformation matrix that maps the view to the screen. By changing this matrix you can accomplish scaling, rotation, and movement (translation) of the view. This type of animation that relies on changing properties and redrawing an image is referred to as tweening animation. Essentially LayoutAnimation is tweening animation of the transformation matrix of the views in a layout. A LayoutAnimation that is specified on a layout is applied to all the views in that layout.

These are the tweening animation types that can be applied to a layout:

  • Scale animation. Used to make a view smaller or larger either along the x axis, on the y axis, or on both. You can also specify the pivot point around which you want the animation to take place.
  • Rotate animation. Used to rotate a view around a pivot point by a certain number of degrees.
  • Translate animation. Used to move a view along the x axis or the y axis.
  • Alpha animation. Used to change the transparency of a view.

These animations are defined as XML files in the /res/anim subdirectory. Create /res/anim/scale.xml file with following content.


    android:startOffset="100" />

If your application dynamically adds or removes views from a layout, and you would like those changes to be animated use the LayoutTransition object to customize how modifications to the view hierarchy in a given layout should be animated. In Android 3.0 and later, any ViewGroup can have changes to its layout animated by simply enabling the android:animateLayoutChanges flag in XML or by adding a LayoutTransition object in Java code.

There are five states during a layout transition that each View in the layout may incur. An application can set a custom animation for each one of the following states:

  • APPEARING. An item that is appearing in the container.
  • DISAPPEARING. An item that is disappearing from the container.
  • CHANGING. An item that is changing because of a layout change, such as a resize, that doesn’t involve views being added or removed.
  • CHANGE_APPEARING. An item changing because of another view appearing.
  • CHANGE_DISAPPEARING. An item changing because of another view disappearing.

Property animation

The animation API is overhauled in 3.0 and 4.0 of Android. This new approach to animations is called property animation. The property animation API is extensive and different enough to refer to the previous animation API (prior to 3.x) as the legacy API even though the previous approach is still valid and not deprecated. The old animation API is in the package android.view.animation. The new animation API is in the package android.animation. Key concepts in the new property animation API are:

  • Animators
  • Value animators
  • Object animators
  • Animator sets
  • Animator builders
  • Animation listeners
  • Property value holders
  • Type evaluators
  • View property animators
  • Layout transitions
  • Animators defined in XML files

Property animation can be applied to various kinds of objects and the effect persists after the animation is over.