You are on page 1of 21

21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.

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

Move and fade Android Views


Combine animations in a sequence or start them simultaneously
Repeat and reverse animations
Adjust the animations’ timing
Become a bit of a rocket scientist. :]
Prerequisites: This Android tutorial is all about animation, so you need basic knowledge of Android programming and familiarity with
Kotlin, Android Studio and XML layouts.
If you’re completely new to Android, you might want to first check out Beginning Android Development Part One.

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.

Click any item on the list.

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.

How do Property Animations Work?


Before you work with the first animation, let’s take a walk down theory road so that you’re clear on the logic behind the magic. :]
Imagine that you need to animate a rocket launch from the bottom edge to the top edge of the screen and that the rocket should make it
exactly in 50 ms.
Here’s a plotted graph that shows how the rocket’s position changes over time:

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:

Here is how this LinearInterpolator responds to time change:

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…

Your First Animation


Take some time to familiarize yourself with the project before you move on. The package
com.raywenderlich.rocketlauncher.animationactivities contains BaseAnimationActivity and all other activities that extend
this class.

https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 6/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com

Open activity_base_animation.xml file in the res/layout folder.


In the root, you’ll find a FrameLayout that contains two instances of ImageView with images: one has rocket.png and the other has
doge.png. Both have android:layout_gravity set to bottom|center_horizontal to render the images at the bottom-center of the
screen.
Note: You’ll do a lot of file navigation in this tutorial. Use these handy shortcuts in Android Studio to move between things easily:
Navigate to any file with command + shift + O on Mac / Ctrl + Shift + N on Linux and Windows
Navigate to a Kotlin class with command + O on Mac / Ctrl + N on Linux and Windows
Navigate to previously opened file with command + E on Mac / Ctrl + E on Linux and Windows
BaseAnimationActivity is a super class of all other animation activities in this app.
Open BaseAnimationActivity.kt and have a look inside. At the top are View member variables that are accessible from all animation
activities:
rocket is the view with the image of the rocket
doge is the view that contains the Doge image
frameLayout is the FrameLayout that contains both rocket and doge
screenHeight will equal the screen height for the sake of convenience
Note that rocket and doge are both of type ImageView, but you declare each as a View since property animations work with all Android
Views. Views are also declared as lateinit values since they will be set before they are used. They will be set in the onCreate() method
of the Activity, well before they are used elsewhere.
Take a look at onCreate() to observe the code:
// 1

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()

Here is what you’ve got going on with this code:


. Call onCreate() on the superclass and then setContentView(...) with the layout file.

2. Find all of the views in the currently set XML layout and bind FrameLayout, rocket and doge to their corresponding variables.

. Set a onClickListener on FrameLayout.

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

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

//2

valueAnimator.addUpdateListener {

// 3

val value = it.animatedValue as Float

// 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.

4. Change the rocket’s position by setting its translationY value.

. 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!

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

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()

Can you spot the difference?


. 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!

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 :]

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:

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

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:

https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 11/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com

. Call ObjectAnimator.ofObject() and give it the following arguments:


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.
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

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

// 2

positionAnimator.addUpdateListener {

val value = it.animatedValue as Float

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

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:


. Create a new ValueAnimator.

2. Attach an AnimatorUpdateListener to the ValueAnimator that updates the rocket’s position.

. Create an ObjectAnimator, a second animator that updates the rocket’s rotation.

4. Create a new instance of AnimatorSet.

. 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.

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()

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 {

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

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()

In the above code you just created three animators:


. positionAnimator — for changing positions of both rocket and doge.

2. rotationAnimator — for rotating Doge.

. 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:
. 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.

https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 15/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com

. Show a toast message when the animation starts.


4. And another toast when it ends.
. Start the animation as usual.
Run the app. Select Animation events. Tap on the screen. Look at the messages!

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

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

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.

REVERSE — reverses the animation’s direction with every iteration.


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! :]

. …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.

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

Declaring Animations in XML


You’ve made it to the best part of this tutorial. In this final section, you’ll learn how to declare once and use everywhere — yes, that’s
right, you’ll be able to reuse your animations with impunity.
By defining animations in XML, you allow reuse of animations throughout your code base.
Defining animations in XML bears some resemblance to composing view layouts.
The starter project has an animation XML in res/animator named jump_and_blink.xml. Open the file in the editor, you should see this:
<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

android:ordering="together">

</set>

The following XML tags are available to you:


set — the same as AnimatorSet.

https://www.raywenderlich.com/2785491-android-animation-tutorial-with-kotlin 17/21
21/10/21 10:12 Android Animation Tutorial with Kotlin | raywenderlich.com

animator — the same as ValueAnimator.


objectAnimator — you guessed correctly; it stands for ObjectAnimator.
When using an AnimatorSet in XML, you nest the ValueAnimator and ObjectAnimator objects inside it, similar to how you nest View
objects inside ViewGroup objects (RelativeLayout, LinearLayout, etc.) in layout XML files.
Replace the contents of jump_and_blink.xml with the following code:
<?xml version="1.0" encoding="utf-8"?>

<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

val rocketAnimatorSet = AnimatorInflater.loadAnimator(this, R.animator.jump_and_blink) as AnimatorSet


// 2

rocketAnimatorSet.setTarget(rocket)

// 3

val dogeAnimatorSet = AnimatorInflater.loadAnimator(this, R.animator.jump_and_blink) as AnimatorSet

// 4

dogeAnimatorSet.setTarget(doge)

// 5

val bothAnimatorSet = AnimatorSet()

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()

In the above code, you’re doing a few things:


. First, you load AnimatorSet from R.animator.jump_and_blink file, just like you normally would to inflate a view layout.

2. Then you set rocket as the target for just-loaded animator.

. Load the animator from the same file once again.


4. Rinse and repeat for doge object.

. Now you create a third AnimatorSet and set it up to play the first two simultaneously.

6. Set the duration for the root animator and start.


7. Whew! Rest just a little bit :]
Build and run. Select Jump and blink (Animations in XML) in the list. Tap to see your handiwork.

You should see Doge jumping, disappearing and then returning back to the ground safely :]

Where To Go From Here?


You can download the completed project by clicking on the Download Materials button at the top or bottom of the tutorial.
During this tutorial you:
Created and used property animations with ValueAnimator and ObjectAnimator.
Set up the time interpolator of your choice for your animation.
Animate position, rotation and color for View.
Combined animations together.
Used the spectacular ViewPropertyAnimator with the help of animate().
Repeated your animation.
Defined the animation in XML for reuse across the project.
Basically, you just gained Android animation super-powers.
If you’re hungry for more, check out the available time interpolators in Android’s documentation (see Known Indirect Subclasses). If
you’re not happy with either of them, you can create your own. You can also set Keyframes for your animation to make them very
sophisticated.
Android has other animation systems like View animations and Drawable Animations. You can also make use of Canvas and OpenGL
ES APIs to create animations. Stay tuned :]

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

All videos. All books.


One low price.
The mobile development world moves quickly — and you don’t want to get left behind. Learn iOS, Swift, Android, Kotlin, Dart, Flutter
and more with the largest and highest-quality catalog of video courses and books on the internet.

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

You might also like