Tuesday, December 3, 2013

Handle end of animation for AnimationDrawable

I have a old exercise "Create frame animation with AnimationDrawable", which play animation repeatly without handle end of the animation. In this exercise, I will do something when the animation end.

AnimationDrawable have no any Listener for the end of animation, and also I cannot use the isRunning() method to determine the end of animation. Finally, I calculate the total duration of the animation using its getNumberOfFrames() and getDuration(). And then use Timer and TimerTask to schedule a Runnable() run when the time reached.

First of all, modify /res/anim/anim_android.xml to set android:oneshot="true", re-use the layout, main.xml, and the frame pictures. All of them can be found here.

Main code:
package com.exercise.AndroidAnimation;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

public class AndroidAnimationActivity extends Activity {
 AnimationDrawable myAnimationDrawable;
 Timer timer;
 MyTimerTask myTimerTask;
    public void onCreate(Bundle savedInstanceState) {
        ImageView myAnimation = (ImageView)findViewById(R.id.myanimation);
         = (AnimationDrawable)myAnimation.getDrawable();

          new Runnable(){

     public void run() {
        //Calculate the total duration
        int duration = 0;
        for(int i = 0; i < myAnimationDrawable.getNumberOfFrames(); i++){
         duration += myAnimationDrawable.getDuration(i);
        timer = new Timer();
        myTimerTask = new MyTimerTask();
        timer.schedule(myTimerTask, duration);
    class MyTimerTask extends TimerTask {

  public void run() {
   runOnUiThread(new Runnable(){
    public void run() {
       "Animation Stopped", 

download filesDownload the files.

Start main activity after splash screen with animation

No comments: