Repeating Android Animations with AnimatorSet

The Android Honeycomb 3.0 (and newer) animation library has a nice little class called AnimatorSet (not to be confused with the older AnimationSet) that lets you organize animations either to be played together, or to be played sequentially. In this case, I needed to create an infinitely looping image fader that cycled through ImageView objects on the screen.

The ValueAnimator class has a nice setRepeatCount() method that would let me just set up my animation as running forever - but AnimatorSet extends Animator, not ValueAnimator, so you don’t get access to that. Setting the repeat to infinite for each Animator you put in the AnimationSet won’t work if you’re sequencing some animations (fade image 1, fade image 2, fade image 3, repeat), but it would work for two images if you set it to reverse itself.

Instead, the solution is to use an AnimatorListenerAdapter that listens for your animation set ending, and then starts the animation again. Make the animation a member of your fragment or activity, and then just put something similar to this in your listener:

mAnimationSet.addListener(new AnimatorListenerAdapter() { 
  @Override public void onAnimationEnd(Animator animation) {