Android Animation Tutorial with Kotlin

Lisa Luo
Update note: This tutorial has been updated to Kotlin and Android Studio 3.0 by Lisa Luo. The original tutorial was written by Artem Kholodnyi.

Android animation

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

Many animation. Such code. Fast rocket.

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 Rocket Launcher Starter. Import it into Android Studio 3.0 Beta 7 or later, then 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.

list

Click any item on the list.

doge_rocket

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:

linear-interpolator

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

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.

frames

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

linear-interpolator

Here is how this LinearInterpolator responds to time change:

table_linear

Depending on the time, the rocket position changes at a constant speed, or linearly.

AccelerateInterpolator

Animations can also have non-linear interpolators. One such example is the AccelerateInterpolator, which looks much more interesting:

table_acc

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.

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

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 a type of 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 are null until the layout is inflated and bound in the appropriate lifecycle event, e.g. onCreate() in an Activity.

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 { onStartAnimation() }

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

  1. Call onCreate() on the superclass and then setContentView(...) with the layout file.
  2. Apply XML layout and bind FrameLayout, rocket and doge to their corresponding views
  3. Set 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 {
  val value = it.animatedValue as Float
  rocket.translationY = value
}

//5
valueAnimator.interpolator = LinearInterpolator()
valueAnimator.duration = BaseAnimationActivity.Companion.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 float; 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 = BaseAnimationActivity.Companion.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 = BaseAnimationActivity.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.

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 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 Android constants Color.YELLOW, 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 = BaseAnimationActivity.Companion.DEFAULT_ANIMATION_DURATION
objectAnimator.start()

Here’s what you’re doing:

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

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 = BaseAnimationActivity.Companion.DEFAULT_ANIMATION_DURATION
objectAnimator.start()

In the code above, you:

  1. 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 ComtextCompat.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!
  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 :]

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 = BaseAnimationActivity.Companion.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(BaseAnimationActivity.Companion.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 = BaseAnimationActivity.Companion.DEFAULT_ANIMATION_DURATION
animatorSet.start()

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 = BaseAnimationActivity.Companion.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

Note: You also can 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

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

In here, you:

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

  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 the repeat count at 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. :]

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
  • 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)
  // 6
  bothAnimatorSet.duration = BaseAnimationActivity.Companion.DEFAULT_ANIMATION_DURATION
  bothAnimatorSet.start()

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

  1. 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
  3. Load the animator from the same file once again
  4. Rinse and repeat for doge object
  5. 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.

jump-n-blink

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

Where To Go From Here

You can grab the final project here.

During this tutorial you:

  • Created and used property animations with ValueAnimator and ObjectAnimator
  • Set up time interpolator of your choice for your animation
  • Animated 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 animations systems like View animations and Drawable Animations. You can also make use of Canvas and OpenGL ES APIs to create animations. Stay tuned :]

I hope you enjoyed the Introduction to Android Animations tutorial. Chime in with your questions, ideas and feedback in the forums below!

Team

Each tutorial at www.raywenderlich.com is created by a team of dedicated developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Lisa Luo

lisa is currently an ios and android engineer at kickstarter.com
she enjoys art, the outdoors, music, and the indoors.

Other Items of Interest

Big Book SaleAll raywenderlich.com iOS 11 books on sale for a limited time!

raywenderlich.com Weekly

Sign up to receive the latest tutorials from raywenderlich.com each week, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

PragmaConf 2016 Come check out Alt U

Our Books

Our Team

Video Team

... 19 total!

iOS Team

... 73 total!

Android Team

... 20 total!

Unity Team

... 10 total!

Articles Team

... 15 total!

Resident Authors Team

... 18 total!

Podcast Team

... 7 total!

Recruitment Team

... 9 total!