Thursday, October 21, 2010

Frame animation - How to know when animation ends?

In related to my earlier post how to use frame animation and implement a circular spinner, i noted a important factor of AnimationDrawable.

I wanted to do some work once the frame animation ends.I looked for animation listener for AnimationDrawable, unfortunately animationDrawable class doesnot have facility to listen for animationlistener object.

SO when googled i found out some suggestions and help in forums. So i am gonna share what i tried out.

1 - We need to calculate the total duration of each frame shown, using getNumberOfFrames() and getDuration() apis.

2 - As soon as the animation is started, Start a timer which will trigger timertask after the total duration. You can conclude now that animation would have ideally stopped. Then you can use stop api to stop the animation.



animation = new AnimationDrawable();

animation.addFrame(getResources().getDrawable(R.drawable.gradient_25), 500);
animation.addFrame(getResources().getDrawable(R.drawable.gradient_50), 500);
animation.addFrame(getResources().getDrawable(R.drawable.gradient_75), 500);
animation.addFrame(getResources().getDrawable(R.drawable.gradient_100), 500);
animation.setOneShot(true);

// Code continues................
// Code continues.................

Button start = (Button ) findViewById(R.id.start);
start.setOnClickListener(new OnClickListener ()
{
public void onClick(View v)
{
animation.start();

long totalDuration = 0;
for(int i = 0; i< animation.getNumberOfFrames();i++){
totalDuration += animation.getDuration(i);
}
Timer timer = new Timer();

TimerTask timerTask = new TimerTask(){
@Override
public void run() {

animation.stop();
}
}};
timer.schedule(timerTask, totalDuration);
}

});



Note: Once you call start on animation object, you need to call 'stop()' on the animation object to see the animation again when start() called again. otherwise, animation wont start.

3 comments:

  1. Hello Boss..! I need a sample Drag And Drop Example.. Help me..!!

    ReplyDelete
  2. Thanks for the solution!!!It Works great!!

    ReplyDelete
  3. Thats my problem, and now solved. Thanks

    ReplyDelete