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;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView myAnimation = (ImageView)findViewById(R.id.myanimation);
myAnimationDrawable
= (AnimationDrawable)myAnimation.getDrawable();
myAnimation.post(
new Runnable(){
@Override
public void run() {
myAnimationDrawable.start();
}
});
//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 {
@Override
public void run() {
timer.cancel();
runOnUiThread(new Runnable(){
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Animation Stopped",
Toast.LENGTH_SHORT).show();
}});
}
}
}
Download the files.
Next:
- Start main activity after splash screen with animation
Thank you
ReplyDelete