Playing Animators Together
For more sophisticated animation choreography, this will not do the trick. For example, to complete the
illusion of a sunset, it would be nice to show the sky turning from orange to a midnight blue after the
sun goes down.
This can be done by using an AnimatorListener, which tells you when an animation completes. So
you could write a listener that waits until the end of the first animation, at which time you can start the
second night sky animation. This is a huge hassle, though, and requires a lot of listeners. It is much
easier to use an AnimatorSet.
First, build out the night sky animation and delete your old animation start code.
Listing 32.14 Building night animation (SunsetFragment.java)
private void startAnimation() {
...
sunsetSkyAnimator.setEvaluator(new ArgbEvaluator());
ObjectAnimator nightSkyAnimator = ObjectAnimator
.ofInt(mSkyView, "backgroundColor", mSunsetSkyColor, mNightSkyColor)
.setDuration(1500);
nightSkyAnimator.setEvaluator(new ArgbEvaluator());
heightAnimator.start();
sunsetSkyAnimator.start();
}
And then build and run an AnimatorSet.
Listing 32.15 Building animator set (SunsetFragment.java)
private void startAnimation() {
...
ObjectAnimator nightSkyAnimator = ObjectAnimator
.ofInt(mSkyView, "backgroundColor", mSunsetSkyColor, mNightSkyColor)
.setDuration(1500);
nightSkyAnimator.setEvaluator(new ArgbEvaluator());
AnimatorSet animatorSet = new AnimatorSet();
animatorSet
.play(heightAnimator)
.with(sunsetSkyAnimator)
.before(nightSkyAnimator);
animatorSet.start();
}
An AnimatorSet is nothing more than a set of animations that can be played together. There are a few
ways to build one, but the easiest way is to use the play(Animator) method you used above.
When you call play(Animator), you get an AnimatorSet.Builder, which allows you to build a chain
of instructions. The Animator passed into play(Animator) is the “subject” of the chain. So the chain
of calls you wrote here could be described as, “Play heightAnimator with sunsetSkyAnimator; also,
play heightAnimator before nightSkyAnimator.” For complicated AnimatorSets, you may find it
necessary to call play(Animator) a few times, which is perfectly fine.
Run your app one more time and savor the soothing sunset you have created. Magic.