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 2 of 4 of this article. Click here to view the first page.

Launch the Rocket

Doge isn’t going anywhere unless you initiate the rocket launch, and it’s the best animation to start with because it’s pretty easy. Who’d have thought that rocket science is so simple?

Open LaunchRocketValueAnimatorAnimationActivity.kt, and add the following code to the body of onStartAnimation():

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

//2
valueAnimator.addUpdateListener {
  // 3
  val value = it.animatedValue as Float
  // 4
  rocket.translationY = value
}

//5
valueAnimator.interpolator = LinearInterpolator()
valueAnimator.duration = DEFAULT_ANIMATION_DURATION

//6
valueAnimator.start()
  1. Create an instance of ValueAnimator by calling the static method ofFloat. It accepts the floating point numbers that’ll apply to the specified property of the animated object over time. In this case, the values start at 0f and end with -screenHeight. Android starts screen coordinates at the top-left corner, so the rocket’s Y translation changes from 0 to the negative of the screen height — it moves bottom to top.
  2. Call addUpdateListener() and pass in a listener. ValueAnimator calls this listener with every update to the animated value — remember the default delay of 10 ms.
  3. Get the current value from the animator and cast it to a float; the current value type is float because you created the ValueAnimator with ofFloat.
  4. Change the rocket’s position by setting its translationY value.
  5. Set up the animator’s duration and interpolator.
  6. Start the animation.

Build and run. Select Launch a Rocket in the list. You’ll get a new screen. Tap it!

linear-launch

That was fun, right? :] Don’t worry about Doge getting left behind — he’ll catch his rocketship to the moon a bit later.

Put a Spin on It

How about giving the rocket a little spin action? Open RotateRocketAnimationActivity.kt and add the following to onStartAnimation():

// 1
val valueAnimator = ValueAnimator.ofFloat(0f, 360f)

valueAnimator.addUpdateListener {
  val value = it.animatedValue as Float
  // 2
  rocket.rotation = value
}

valueAnimator.interpolator = LinearInterpolator()
valueAnimator.duration = DEFAULT_ANIMATION_DURATION
valueAnimator.start()

Can you spot the difference?

  1. Changing the valueAnimator values to go from 0f to 360f causes the rocket to make a full turn. Note that you could create a U-turn effect with 0f to 180f.
  2. Instead of setting translationY, you set the rocket’s rotation because that’s what needs to change.

Build, run and select Spin a rocket. Tap on the new screen:

Accelerate the Launch

Open AccelerateRocketAnimationActivity.kt and add the following code to your old friend onStartAnimation():

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

// 2 - Here set your favorite interpolator
valueAnimator.interpolator = AccelerateInterpolator(1.5f)
valueAnimator.duration = DEFAULT_ANIMATION_DURATION

// 3
valueAnimator.start()

The above code is identical to onStartAnimation() in LaunchRocketValueAnimationActivity.kt except for one line: the interpolator used to set valueAnimator.interpolator.

Build, run and select Accelerate a rocket in the list. Tap on the new screen to see how your rocket behaves. Notice how it starts slowly and then it gets accelerated.

Again, we see that poor Doge doesn’t catch the rocket to the moon…poor fella. Hang in there, buddy!

accelerate

Since you used AccelerateInterpolator, you should see your rocket accelerating after liftoff. Feel free to play around with interpolators if you’d like. I’ll sit here and wait. I promise :]

Which Properties Can You Animate?

Until now, you’ve only animated position and rotation for View, but ValueAnimator doesn’t care what you do with the value that it supplies.

You can tell ValueAnimator to animate the value using any of the following types:

  • float if you create ValueAnimator instance with ofFloat.
  • int if you do it with ofInt.
  • ofObject is for the cases when float or int is not enough — it’s often used to animate colors.

You can also animate any property of View. Some examples are:

  • scaleX and scaleY – these allow you to scale the view by the x-axis or y-axis independently, or you can call both with the same value to animate the view’s size.
  • translationX and translationY – these allow you to change the view’s on-screen position.
  • alpha – animate view’s transparency; 0 stands for completely transparent and 1 for completely opaque.
  • rotation – rotates the view on screen; the argument is in degrees, so 360 means a full clockwise turn. You may specify negative values as well, for instance, -90 means a counterclockwise quarter-turn.
  • rotationX and rotationY – the same as rotation but along the x-axis and y-axis. These properties allow you to rotate in 3D.
  • backgroundColor – lets you set a color. The integer argument must specify a color as the Android constants Color.YELLOW and Color.BLUE do.

ObjectAnimator

Meet ObjectAnimator, a subclass of ValueAnimator. If you only need to animate a single property of a single object, ObjectAnimator may just be your new best friend.

Unlike ValueAnimator, where you must set a listener and do something with a value, ObjectAnimator can handle those bits for you almost automagically. :]

Go to LaunchRocketObjectAnimatorAnimationActivity.kt class and enter the following code:

// 1
val objectAnimator = ObjectAnimator.ofFloat(rocket, "translationY", 0f, -screenHeight)

// 2
objectAnimator.duration = DEFAULT_ANIMATION_DURATION
objectAnimator.start()

Here’s what you’re doing:

  • rocket is the object to animate.
  • The object must have a property corresponding to the name of the property you wish to change, which in this example is “translationY”. You’re able to do this because rocket is an object of class View, which, in its base Java class, has an accessible setter with setTranslationY().
  1. Creating an instance of ObjectAnimator (like you did with ValueAnimator) except that the former takes two more parameters:
  2. You set the duration for the animation and start it.

Run your project. Select Launch a rocket (ObjectAnimator) in the list. Tap on the screen.

linear-launch

The rocket behaves the same as it did with ValueAnimator, but with less code. :]

Note: There’s a limitation to ObjectAnimator — it can’t animate two objects simultaneously. To work around it, you create two instances of ObjectAnimator.

Consider your use cases and the amount of coding required when you decide to use ObjectAnimator or ValueAnimator.

Animating Color

Speaking of use cases, there’s animating colors to consider. Neither ofFloat() nor ofInt() can construct your animator and get good results with colors. You’re better off using ArgbEvaluator.

Open ColorAnimationActivity.kt and put this code into onStartAnimation():

//1
val objectAnimator = ObjectAnimator.ofObject(
  frameLayout,
  "backgroundColor",
  ArgbEvaluator(),
  ContextCompat.getColor(this, R.color.background_from),
  ContextCompat.getColor(this, R.color.background_to)
)

// 2
objectAnimator.repeatCount = 1
objectAnimator.repeatMode = ValueAnimator.REVERSE

// 3
objectAnimator.duration = DEFAULT_ANIMATION_DURATION
objectAnimator.start()

In the code above, you:

  • frameLayout — the object with the property to be animated.
  • "backgroundColor" — the property you want to animate.
  • ArgbEvaluator() — an additional argument that specifies how to interpolate between two different ARGB (alpha, red, green, blue) color values.
  • Start and end color values — here you make use of ContextCompat.getColor() to get the color resource id of a custom color specified in your colors.xml.
  1. Call ObjectAnimator.ofObject() and give it the following arguments:
  2. Set the number of times the animation will repeat by setting the object’s repeatCount value. Then you set its repeatMode to define what the animation does when it reaches the end. More on this soon!
  3. Set duration and start the animation.

Build and run. Pick the Background color item and tap on the screen.

bg-color

That’s amazing! Hey, you’re getting the hang of this pretty quickly. That’s a buttery-smooth background color change :]