time

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.

<animation-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item
        android:drawable="@drawable/colored_ball1"
        android:duration="50" />

    <item
        android:drawable="@drawable/colored_ball2"
        android:duration="50" />

    <item
        android:drawable="@drawable/colored_ball3"
        android:duration="50" />
</animation-list>

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:

imageView.setBackgroundResource(R.drawable.frame_animation);

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.

Animation XML files can support the following elements: <alpha>, <scale>, <translate>, <rotate>. <set> element can be used to group multiple animation elements.

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);
someView.startAnimation(animation);

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"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:duration="300"
    android:fromXScale="0.0"
    android:fromYScale="0.0"
    android:toXScale="1.0"
    android:toYScale="1.0"
    android:fillAfter="true"/>

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:

android:fromTRANSFORMATION
android:toTRANSFORMATION
  • 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:

tvLabel.startAnimation(animation);

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

Let's decorate Button with ripple effect. First, you have to create a xml file in your drawable resource directory. Create a ripple_effect.xml file and add following code.

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

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

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple_effect"
    android:padding="16dp"
    android:text="Start animation" />

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:fillAfter="true">

    <alpha
        android:duration="1000"
        android:fromAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="1.0" />
</set>

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:fillAfter="true">

    <alpha
        android:duration="1000"
        android:fromAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="0.0" />
</set>

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"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="600"
        android:repeatMode="restart"
        android:repeatCount="infinite"
        android:interpolator="@android:anim/cycle_interpolator"/>
</set>

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.

<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:fillAfter="true">

   <translate
        android:fromXDelta="0%p"
        android:toXDelta="75%p"
        android:duration="800" />
</set>

Slide Up Animation.

File slide_up.xml in res/anim.

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

    <scale
        android:duration="500"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/linear_interpolator"
        android:toXScale="1.0"
        android:toYScale="0.0" />
>/set<

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:fillAfter="true">

    <scale
        android:duration="500"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

This is just the opposite of slide_up.xml.

AndroidViewAnimations.

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.

YoYo.with(Techniques.Shake)
    .duration(700)
    .playOn(tvLabel);

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.

<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator">

    <scale
    android:fromXScale="1"
    android:toXScale="1"
    android:fromYScale="0.1"
    android:toYScale="1.0"
    android:duration="500"
    android:pivotX="50%"
    android:pivotY="50%"
    android:startOffset="100" />
</set>

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.

comments powered by Disqus