Android Animation Tutorial With Kotlin
Android Animation Tutorial With Kotlin
com
Subscribe now to get full access to our entire catalogue of 4,000+ mobile development videos and 50+ online books.
Home
Android & Kotlin Tutorials
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.
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 1/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
By Kevin D Moore
May 13 2019 · Article (35 mins) · Beginner
5/5
27 Ratings
Update note: This tutorial has been updated to Kotlin and Android Studio 3.4 by Kevin Moore. The original tutorial was written
by Artem Kholodnyi and the update was by Lisa Luo.
It’s hard to imagine the mobile experience without animated elements–they’re fun, beautiful and hold the power of not only guiding
users gracefully through an app, but also bringing screens to life.
Building animations that make on-screen objects seem alive may look like aerospace engineering at first, but fear not! Android has quite
a few tools to help you create animations with relative ease.
You’ll learn to get comfortable with some essential animation tools in this tutorial as you work through launching Doge on a rocket into
space (maybe even to the moon) and hopefully get it back safely on the ground :]
By creating these Doge animations, you’ll learn how to:
Create property animations — the most useful and simple Android animations
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 2/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
Getting Started
Animations are such a fun topic to explore! The best way to master building animations is by getting your hands dirty in code. :]
First, download the project files at the top or bottom of the tutorial by clicking on the Download Materials button. Import it into
Android Studio 3.4 or later, then build and run it on your device. You’ll find everything you need to get going quickly.
Your device will display a list of all the animations you’ll implement.
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 3/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
You should see two static images: Doge and the rocket, and Doge is ready to take a ride. For now, all the screens are the same and none
are yet animated.
The animation above appears to be smooth and continuous. However, smartphones are digital and work with discrete values. Time does
not flow continuously for them; it advances by tiny steps.
Animation consists of many still images, also known as frames, that are displayed one by one over at a specified time period. The
concept today is the same as it was for the first cartoons, but the rendering is a little different.
Elapsed time between frames is named frame refresh delay — it’s 10 ms by default for property animations.
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 4/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
Here’s where animation is different than it was in the early days of film: when you know the rocket moves at a constant speed, you can
calculate the position of the rocket at any given time.
You see six animation frames shown below. Notice that:
In the beginning of the animation, the rocket is at the bottom edge of the screen.
The rocket’s position moves upward by the same fraction of its path with every frame.
By the end of the animation, the rocket is at the top edge of the screen.
TL/DR: When drawing a given frame, you calculate the rocket’s position based on the duration and frame refresh rate.
Fortunately, you don’t have to do all the calculations manually because ValueAnimator is happy to do it for you. :]
To set up an animation, you simply specify the start and end values of the property being animated, as well as the duration. You’ll also
need to add a listener to call, which will set a new position for your rocket for each frame.
Time Interpolators
You probably noticed that your rocket moves with constant speed during the entire animation — not terribly realistic. Material Design
encourages you to create vivid animations that catch the user’s attention while behaving in a more natural way.
Android’s animation framework makes use of time interpolators. ValueAnimator incorporates a time interpolator – it has an object that
implements the TimeInterpolator interface. Time interpolators determine how the animated value changes over time.
Have a look again at the graph of position changes over time in the simplest case — a Linear Interpolator:
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 5/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
Depending on the time, the rocket position changes at a constant speed, or linearly.
Animations can also have non-linear interpolators. One such example is the AccelerateInterpolator, which looks much more
interesting:
It squares the input value, making the rocket start slowly and accelerate quickly — just like a real rocket does!
That’s pretty much all the theory you need to know to get started, so now it’s time for…
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 6/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_base_animation)
// 2
rocket = findViewById(R.id.rocket)
doge = findViewById(R.id.doge)
frameLayout = findViewById(R.id.container)
// 3
frameLayout.setOnClickListener {
// 4
onStartAnimation()
2. Find all of the views in the currently set XML layout and bind FrameLayout, rocket and doge to their corresponding variables.
4. Call onStartAnimation() whenever the user taps the screen. This is an abstract method defined by each of the activities that
extend BaseAnimationActivity.
This basic code is shared by all of the Activities you will be editing in this tutorial. Now that you’re familiar with it, it’s time to start
customizing!
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
//2
valueAnimator.addUpdateListener {
// 3
// 4
rocket.translationY = value
//5
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 7/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
valueAnimator.interpolator = LinearInterpolator()
valueAnimator.duration = DEFAULT_ANIMATION_DURATION
//6
valueAnimator.start()
. 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.
. 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.
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
valueAnimator.addUpdateListener {
// 2
rocket.rotation = value
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 8/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
valueAnimator.interpolator = LinearInterpolator()
valueAnimator.duration = DEFAULT_ANIMATION_DURATION
valueAnimator.start()
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:
valueAnimator.addUpdateListener {
rocket.translationY = value
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!
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 9/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
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 :]
// 2
objectAnimator.duration = DEFAULT_ANIMATION_DURATION
objectAnimator.start()
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 10/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
. Creating an instance of ObjectAnimator (like you did with ValueAnimator) except that the former takes two more parameters:
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().
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.
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
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()
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 11/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
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.
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!
. Set duration and start the animation.
Build and run. Pick the Background color item and tap on the screen.
That’s amazing! Hey, you’re getting the hang of this pretty quickly. That’s a buttery-smooth background color change :]
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
// 2
positionAnimator.addUpdateListener {
rocket.translationY = value
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 12/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
// 3
// 4
// 5
animatorSet.play(positionAnimator).with(rotationAnimator)
// 6
animatorSet.duration = DEFAULT_ANIMATION_DURATION
animatorSet.start()
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.
.translationY(-screenHeight)
.rotationBy(360f)
.setDuration(DEFAULT_ANIMATION_DURATION)
.start()
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 13/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
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 {
rocket?.translationY = value
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
positionAnimator.addUpdateListener {
rocket.translationY = value
doge.translationY = value
//2
rotationAnimator.addUpdateListener {
doge.rotation = value
//3
animatorSet.play(positionAnimator).with(rotationAnimator)
animatorSet.duration = DEFAULT_ANIMATION_DURATION
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 14/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
animatorSet.start()
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
animator.addUpdateListener {
val value = it.animatedValue as Float
rocket.translationY = value
doge.translationY = value
// 2
animator.addListener(object : Animator.AnimatorListener {
// 3
.show()
// 4
.show()
finish()
})
// 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:
. 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.
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 15/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
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
})
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.
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
animator.addUpdateListener {
val value = it.animatedValue as Float
rocket.translationY = value
doge.translationY = value
// 2
animator.repeatMode = ValueAnimator.REVERSE
// 3
animator.repeatCount = 3
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 16/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
// 4
animator.duration = 500L
animator.start()
In here, you:
. Create an animator, as usual.
2. You can set the repeatMode to either of the following:
RESTART — restarts the animation from the beginning.
You should see your rocket jumping like a grasshopper! Take that, Elon Musk. :]
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:ordering="together">
</set>
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 17/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:ordering="together">
<objectAnimator
android:propertyName="alpha"
android:duration="1000"
android:repeatCount="1"
android:repeatMode="reverse"
android:interpolator="@android:interpolator/linear"
android:valueFrom="1.0"
android:valueTo="0.0"
android:valueType="floatType"/>
<objectAnimator
android:propertyName="translationY"
android:duration="1000"
android:repeatCount="1"
android:repeatMode="reverse"
android:interpolator="@android:interpolator/bounce"
android:valueFrom="0"
android:valueTo="-500"
android:valueType="floatType"/>
</set>
Here you declare a root element, set tag. Its ordering attribute can be either together or sequential. It’s together by default, but
you may prefer to specify it for clarity. The set tag has two child XML tags, each of which is an objectAnimator.
Take a look at the following attributes of objectAnimator:
android:valueFrom and android:valueTo — specify start and end values like you did when you created an instance of
ObjectAnimator.
android:valueType — value type; either floatType or intType.
android:propertyName — the property you want to animate without the set part.
android:duration — duration of the animation.
android:repeatCount — the same as with setRepeatCount.
android:repeatMode — the same as with setRepeatMode.
android:interpolator — specify interpolator; it usually starts with @android:interpolator/. Start typing this and Android
Studio will show all available interpolators under autocomplete options.
You can’t specify your target object here, but you can do it later in Kotlin.
In the last block, you added two instances of objectAnimator to the AnimatorSet, and they will play together. Now, it’s time to use
them.
Go to XmlAnimationActivity.kt and add the following code to onStartAnimation():
// 1
rocketAnimatorSet.setTarget(rocket)
// 3
// 4
dogeAnimatorSet.setTarget(doge)
// 5
bothAnimatorSet.playTogether(rocketAnimatorSet, dogeAnimatorSet)
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 18/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
// 6
bothAnimatorSet.duration = DEFAULT_ANIMATION_DURATION
bothAnimatorSet.start()
. Now you create a third AnimatorSet and set it up to play the first two simultaneously.
You should see Doge jumping, disappearing and then returning back to the ground safely :]
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 19/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
I hope you enjoyed the Introduction to Android Animations tutorial. Chime in with your questions, ideas and feedback in the forums
below!
raywenderlich.com Weekly
The raywenderlich.com newsletter is the easiest way to stay up-to-date on everything you need to know as a mobile developer.
stevewozniak@apple.com
Get a weekly digest of our tutorials and courses, and receive a free in-depth email course as a bonus!
Add a rating for this content
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 20/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com
https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 21/21