Wednesday, November 17, 2010

Getting animations to work

This is a simple project that will explain how to use animations in android through AnimationDrawable. The documentation was a bit outdated. But you might hit a dead-end if you try to call the animation's start method from within any of the Activity's life-cycle methods.

In this example, there is an ImageView with it's "src" value set to an image. The ImageView's background is set with you own AnimationDrawable, basically an xml in your res/drawable folder. In the activity, the ImageView has a click listener, which creates an AnimationDrawable from the ImageView's background, and just calls the start method of the AnimationDrawable class.

Here is a sample AnimationDrawable described through XML.
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false"
>
    <item android:drawable="@drawable/black" android:duration="200" />
    <item android:drawable="@drawable/cyan" android:duration="200" />
    <item android:drawable="@drawable/green" android:duration="200" />
    <item android:drawable="@drawable/magenta" android:duration="200" />
    <item android:drawable="@drawable/navy" android:duration="200" />
    <item android:drawable="@drawable/orange" android:duration="200" />
    <item android:drawable="@drawable/pink" android:duration="200" />
    <item android:drawable="@drawable/white" android:duration="200" />
    <item android:drawable="@drawable/yellow" android:duration="200" />
</animation-list>
And here is the code that gets your animation started.
imageView = (ImageView) findViewById(R.id.ImageButton01);
        imageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                AnimationDrawable animator = (AnimationDrawable) imageView.getBackground();
                imageView.setImageDrawable(null);
                animator.start();
            }
        });
One point to notice is that, you have to remove the ImageView's "src" value, so that the animation is visible, since the animation works by changing the background of the ImageView, else, your animation would be blocked by the ImageView's "src" image.

Once you are done, you can stop the animation, and reset the ImageView's "src" to it's original image.
// Call this method to stop the animation
    public void stopAnimation(){
        AnimationDrawable animator = (AnimationDrawable) imageView.getBackground();
        animator.stop();
        imageView.setImageResource(R.drawable.icon);
    }
 You can find the whole source code for this example here.