Android Animation Tutorial with Kotlin

In this Android animation tutorial, you will learn how to use property animations to make a fun, beautiful user interface. By Kevin D Moore.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 3 of 4 of this article. Click here to view the first page.

Combining Animations

Animating a view is pretty awesome, but so far you’ve changed only one property and one object at a time. Animations need not be so restrictive.

It’s time to send Doge to the moon! :]

AnimatorSet allows you to play several animations together or in sequence. You pass your first animator to play(), which accepts an Animator object as an argument and returns a builder.

Then you can call the following methods on that builder, all of which accept Animator as an argument:

  • with() — to play the Animator passed as the argument simultaneously with the first one you specified in play().
  • before() — to play it before.
  • after() — to play it after.

You can create chains of calls such as these.

Open LaunchAndSpinAnimatorSetAnimatorActivity.kt in your editor, and put the following code into onStartAnimation():

// 1
val positionAnimator = ValueAnimator.ofFloat(0f, -screenHeight)

// 2
positionAnimator.addUpdateListener {
  val value = it.animatedValue as Float
  rocket.translationY = value
}

// 3
val rotationAnimator = ObjectAnimator.ofFloat(rocket, "rotation", 0f, 180f)
// 4
val animatorSet = AnimatorSet()
// 5
animatorSet.play(positionAnimator).with(rotationAnimator)
// 6
animatorSet.duration = DEFAULT_ANIMATION_DURATION
animatorSet.start()

Here’s what you’re doing in this block:

  1. Create a new ValueAnimator.
  2. Attach an AnimatorUpdateListener to the ValueAnimator that updates the rocket’s position.
  3. Create an ObjectAnimator, a second animator that updates the rocket’s rotation.
  4. Create a new instance of AnimatorSet.
  5. Specify that you’d like to execute positionAnimator together with rotationAnimator.
  6. Just as with a typical animator, you set a duration and call start().

Build and run again. Select the Launch and spin (AnimatorSet). Tap the screen.

launch-n-spin

Doge defies the laws of physics with this one.

There’s a nifty tool to simplify animating several properties of the same object. The tool is called…

ViewPropertyAnimator

One of the greatest things about animation code that uses ViewPropertyAnimator is that it’s easy to write and read — you’ll see.

Open LaunchAndSpinViewPropertyAnimatorAnimationActivity.kt and add the following call to onStartAnimation():

rocket.animate()
    .translationY(-screenHeight)
    .rotationBy(360f)
    .setDuration(DEFAULT_ANIMATION_DURATION)
    .start()

In here, animate() returns an instance of ViewPropertyAnimator so you can chain the calls.

Build and run, select Launch and spin (ViewPropertyAnimator), and you’ll see the same animation as in the previous section.

Compare your code for this section to the AnimatorSet code snippet that you implemented in the previous section:

val positionAnimator = ValueAnimator.ofFloat(0f, -screenHeight)

positionAnimator.addUpdateListener {
  val value = it.animatedValue as Float
  rocket?.translationY = value
}

val rotationAnimator = ObjectAnimator.ofFloat(rocket, "rotation", 0f, 180f)

val animatorSet = AnimatorSet()
animatorSet.play(positionAnimator).with(rotationAnimator)
animatorSet.duration = DEFAULT_ANIMATION_DURATION
animatorSet.start()

Note: ViewPropertyAnimator may provide better performance for multiple simultaneous animations. It optimizes invalidated calls, so they only take place once for several properties — in contrast to each animated property causing its own invalidation independently.

Animating the Same Property of Two Objects

A nice feature of ValueAnimator is that you can reuse its animated value and apply it to as many objects as you like.

Test it out by opening FlyWithDogeAnimationActivity.kt and putting the following code in onStartAnimation():

//1
val positionAnimator = ValueAnimator.ofFloat(0f, -screenHeight)
positionAnimator.addUpdateListener {
  val value = it.animatedValue as Float
  rocket.translationY = value
  doge.translationY = value
}

//2
val rotationAnimator = ValueAnimator.ofFloat(0f, 360f)
rotationAnimator.addUpdateListener {
  val value = it.animatedValue as Float
  doge.rotation = value
}

//3
val animatorSet = AnimatorSet()
animatorSet.play(positionAnimator).with(rotationAnimator)
animatorSet.duration = DEFAULT_ANIMATION_DURATION
animatorSet.start()

In the above code you just created three animators:

  1. positionAnimator — for changing positions of both rocket and doge.
  2. rotationAnimator — for rotating Doge.
  3. animatorSet — to combine the first two animators.

Notice that you set translation for two objects at once in the first animator.

Run the app and select Don’t leave Doge behind (Animating two objects). You know what to do now. To the moon!

Animation Listeners

Animation typically implies that a certain action has occurred or will take place. Typically, whatever happens usually comes at the end of your fancy animation.

You don’t get to observe it, but know that the rocket stops and stays off screen when the animation ends. If you don’t plan to land it or finish the activity, you could remove this particular view to conserve resources.

AnimatorListener — receives a notification from the animator when the following events occur:

  • onAnimationStart() — called when the animation starts.
  • onAnimationEnd() — called when the animation ends.
  • onAnimationRepeat() — called if the animation repeats.
  • onAnimationCancel() — called if the animation is canceled.

Open WithListenerAnimationActivity.kt and add the following code to onStartAnimation():

//1
val animator = ValueAnimator.ofFloat(0f, -screenHeight)

animator.addUpdateListener {
  val value = it.animatedValue as Float
  rocket.translationY = value
  doge.translationY = value
}

// 2
animator.addListener(object : Animator.AnimatorListener {
  override fun onAnimationStart(animation: Animator) {
    // 3
    Toast.makeText(applicationContext, "Doge took off", Toast.LENGTH_SHORT)
        .show()
  }

  override fun onAnimationEnd(animation: Animator) {
    // 4
    Toast.makeText(applicationContext, "Doge is on the moon", Toast.LENGTH_SHORT)
        .show()
    finish()
  }

  override fun onAnimationCancel(animation: Animator) {}

  override fun onAnimationRepeat(animation: Animator) {}
})

// 5
animator.duration = 5000L
animator.start()

The structure of the code above, with the exception of the listener part, should look the same as the previous section. Here’s what you’re doing in there:

  1. Create and set up an animator. You use ValueAnimator to change the position of two objects simultaneously — you can’t do the same thing with a single ObjectAnimator.
  2. Add the AnimatorListener.
  3. Show a toast message when the animation starts.
  4. And another toast when it ends.
  5. Start the animation as usual.

Run the app. Select Animation events. Tap on the screen. Look at the messages!

events

Alternatively, you can set start and end actions on your View by calling withStartAction(Runnable) and withEndAction(Runnable) after animate(). It’s the equivalent to an AnimatorListener with these actions.

Note: You can also add a listener to ViewPropertyAnimator by adding a setListener to a call chain before calling start():
rocket.animate().setListener(object : Animator.AnimatorListener {
  // Your action
})
rocket.animate().setListener(object : Animator.AnimatorListener {
  // Your action
})

Animation Options

Animations are not one-trick ponies that simply stop and go. They can loop, reverse, run for a specific duration, etc.

In Android, you can use the following methods to adjust an animation:

  • repeatCount — specifies the number of times the animation should repeat after the initial run.
  • repeatMode — defines what this animation should do when it reaches the end.
  • duration — specifies the animation’s total duration.

Open up FlyThereAndBackAnimationActivity.kt, and add the following to onStartAnimation().

// 1
val animator = ValueAnimator.ofFloat(0f, -screenHeight)

animator.addUpdateListener {
  val value = it.animatedValue as Float
  rocket.translationY = value
  doge.translationY = value
}

// 2
animator.repeatMode = ValueAnimator.REVERSE
// 3
animator.repeatCount = 3

// 4
animator.duration = 500L
animator.start()

In here, you:

In this case, you set it to REVERSE because you want the rocket to take off and then go back to the same position where it started. Just like SpaceX! :]

  • RESTART — restarts the animation from the beginning.
  • REVERSE — reverses the animation’s direction with every iteration.
  1. Create an animator, as usual.
  2. You can set the repeatMode to either of the following:
  3. …Except you’ll do it twice.
  4. Set a duration and start the animation, as usual.

Note: So why does the third section specify a repeat count of three? Each up-and-down motion consumes two repetitions, so you need three to bring Doge back to earth twice: one to land the first time, and two to launch and land again. How many times would you like to see Doge bounce? Play around with it!

Run the app. Select Fly there and back (Animation options) in the list. A new screen is opened. Tap on the screen.

there-and-back

You should see your rocket jumping like a grasshopper! Take that, Elon Musk. :]