Chris D
Chris D

Reputation: 820

How to check to see if animation is running before starting new animation?

I have a activity where I have multiple ImageViews and when you click on it the ImageView will fade out and fade back in. What I'm trying to figure out is how I can click one ImageView and start the animation and when I click a 2nd one and the animation is still running it will ignore the second one. I think I need to do something with the animationListener but I can't figure out how to use that to check if the animation is running or not before I initiate a new animation. I could have sworn I saw an example that did this but I've been looking for days and can't find it anymore, I'm hoping someone would be able to help out here..... below is the code for my animation:

// Create Animation
protected void fadeAnimation() {
    tempImg.startAnimation(fadeout);
    //Allow animation to finish
    mHandler.postDelayed(new Runnable() {
        public void run() {
        tempImg.startAnimation(fadein);
        }
    }, 1000);
}

Upvotes: 35

Views: 41055

Answers (2)

Claudiu Bele
Claudiu Bele

Reputation: 51

Instead of having to loop possibly in another thread checking if an animation has ended, you could use an animation listener, doing something like this:

// Create Animation
protected void fadeAnimation() {
   fadeout.setAnimationListener(new Animation.AnimationListener(){
         @Override
         public void onAnimationStart(Animation animation) {

         }
         @Override
         public void onAnimationEnd(Animation animation) {
              tempImg.startAnimation(fadein);
         }             
         @Override
         public void onAnimationRepeat(Animation animation) {

         }

   };
   tempImg.startAnimation(fadeout);

}

With this kind of solution you wouldn't need to be actively checking if an animation has finished and time it with the duration of the previous animation.

The onAnimationEnd(Animation) is fired right after the animation has ended. This also solves the issue of users with developer options "on" and animation speed set to "off".

Upvotes: 5

Grimmace
Grimmace

Reputation: 4041

I'm assuming both fadeout and fadein are Animation objects.

Use fadeout.hasEnded() to check if the first has finished before starting your second one.

For more details about the Animation class, see here: http://developer.android.com/reference/android/view/animation/Animation.html

Upvotes: 44

Related Questions