vogella training Android Training Eclipse Training

Android Animations - Tutorial

Lars Vogel

Version 2.1

16.03.2012

Revision History
Revision 0.1 05.01.2011 Lars
Vogel
Created
Revision 0.2 - 2.1 08.02.2011 - 16.03.2012 Lars
Vogel
bug fixes and enhancements

Android Animations

This tutorial describes how to use Animations in Android. The tutorial is based on Eclipse 3.7, Java 1.6 and Android 4.0.


Table of Contents

1. Android Animations
1.1. Overview
1.2. Animations for Activity transition
2. Android Basics
3. Tutorial: View Animation
4. Thank you
5. Questions and Discussion
6. Links and Literature
6.1. Source Code
6.2. Android Resources
6.3. vogella Resources

1. Android Animations

1.1. Overview

Android 3.0 introduced the properties Animation API. This tutorial focus on this new API.

An animation defined by this API allows to define for arbitrary properties a start and end value and apply a time-based change to this attribute.

The property API can be applied on any Java object not only Views.

The superclass of the animation API is the Animation class. Typically the ObjectAnimator class is used to modify the attributes of an object.

You can also add an AnimationListener class to your Animation class. This listener is called in the different phases of the animation. You can use this listener to perfrom actions before or after a certain animation, e.g. add or remove a View from a ViewGroup.

1.2. Animations for Activity transition

Animations can be applied to views but it is also possible to apply them on the transition between Activities.

For this your use the overridePendingTransition() in the current Activity. This method takes two parameters, the out transition of the old Activity and the in transition of the new Activity.

2. Android Basics

The following assumes that you have already basic knowledge in Android development. Please check the Android development tutorial to learn the basics.

3. Tutorial: View Animation

We will create an example to demonstrate the usage of the Properties Animation API.

Create a new Android project "de.vogella.android.animation" with the Activity called "AnimationExampleActivity". Change "main.xml" to the following.

			
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/Button01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="startAnimation"
            android:text="Rotate" />

        <Button
            android:id="@+id/Button04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="startAnimation"
            android:text="Group" >
        </Button>

        <Button
            android:id="@+id/Button03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="startAnimation"
            android:text="Fade" />

        <Button
            android:id="@+id/Button02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="startAnimation"
            android:text="Animate" />

    </LinearLayout>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/icon" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView1"
        android:layout_alignRight="@+id/imageView1"
        android:layout_marginBottom="30dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
		

Create the following menu resource.

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

    <item
        android:id="@+id/item1"
        android:showAsAction="ifRoom"
        android:title="Game">
    </item>

</menu>
		

Change your Activity to the following.

			
package de.vogella.android.animation;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class AnimationExampleActivity extends Activity {

	
/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startAnimation(View view) { float dest = 0; ImageView aniView = (ImageView) findViewById(R.id.imageView1); switch (view.getId()) { case R.id.Button01: dest = 360; if (aniView.getRotation() == 360) { System.out.println(aniView.getAlpha()); dest = 0; } ObjectAnimator animation1 = ObjectAnimator.ofFloat(aniView, "rotation", dest); animation1.setDuration(2000); animation1.start(); // Show how to load an animation from XML // Animation animation1 = AnimationUtils.loadAnimation(this, // R.anim.myanimation); // animation1.setAnimationListener(this); // animatedView1.startAnimation(animation1); break; case R.id.Button02: // Shows how to define a animation via code // Also use an Interpolator (BounceInterpolator) Paint paint = new Paint(); TextView aniTextView = (TextView) findViewById(R.id.textView1); float measureTextCenter = paint.measureText(aniTextView.getText() .toString()); dest = 0 - measureTextCenter; if (aniTextView.getX() < 0) { dest = 0; } ObjectAnimator animation2 = ObjectAnimator.ofFloat(aniTextView, "x", dest); animation2.setDuration(2000); animation2.start(); break; case R.id.Button03: // Demonstrate fading and adding an AnimationListener dest = 1; if (aniView.getAlpha() > 0) { dest = 0; } ObjectAnimator animation3 = ObjectAnimator.ofFloat(aniView, "alpha", dest); animation3.setDuration(2000); animation3.start(); break; case R.id.Button04: ObjectAnimator fadeOut = ObjectAnimator.ofFloat(aniView, "alpha", 0f); fadeOut.setDuration(2000); ObjectAnimator mover = ObjectAnimator.ofFloat(aniView, "translationX", -500f, 0f); mover.setDuration(2000); ObjectAnimator fadeIn = ObjectAnimator.ofFloat(aniView, "alpha", 0f, 1f); fadeIn.setDuration(2000); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.play(mover).with(fadeIn).after(fadeOut); animatorSet.start(); break; default: break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.mymenu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(this, HitActivity.class); startActivity(intent); return true; } }

Create a new Activity called "HitActivity".

			
package de.vogella.android.animation;

import java.util.Random;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class HitActivity extends Activity {
	private ObjectAnimator animation1;
	private ObjectAnimator animation2;
	private Button button;
	private Random randon;
	private int width;
	private int height;
	private AnimatorSet set;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.target);
		width = getWindowManager().getDefaultDisplay().getWidth();
		height = getWindowManager().getDefaultDisplay().getHeight();
		randon = new Random();

		set = createAnimation();
		set.start();
		set.addListener(new AnimatorListenerAdapter() {

			@Override
			public void onAnimationEnd(Animator animation) {
				int nextX = randon.nextInt(width);
				int nextY = randon.nextInt(height);
				animation1 = ObjectAnimator.ofFloat(button, "x", button.getX(),
						nextX);
				animation1.setDuration(1400);
				animation2 = ObjectAnimator.ofFloat(button, "y", button.getY(),
						nextY);
				animation2.setDuration(1400);
				set.playTogether(animation1, animation2);
				set.start();
			}
		});
	}

	public void onClick(View view) {
		String string = button.getText().toString();
		int hitTarget = Integer.valueOf(string) + 1;
		button.setText(String.valueOf(hitTarget));
	}

	private AnimatorSet createAnimation() {
		int nextX = randon.nextInt(width);
		int nextY = randon.nextInt(height);
		button = (Button) findViewById(R.id.button1);
		animation1 = ObjectAnimator.ofFloat(button, "x", nextX);
		animation1.setDuration(1400);
		animation2 = ObjectAnimator.ofFloat(button, "y", nextY);
		animation2.setDuration(1400);
		AnimatorSet set = new AnimatorSet();
		set.playTogether(animation1, animation2);
		return set;
	}
}

		

If you run this example and press the different Buttons, the animation should start. Via the ActionBar you can navigate to your other Activity.

4. Thank you

Please help me to support this article:

Flattr this

5. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

6. Links and Literature

6.1. Source Code

Source Code of Examples

6.3. vogella Resources

Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java and compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put everything you have under distributed version control system