Build awesome animations with 7 lines of code using ConstraintLayout

Leonardo Pirro
AndroidPub
Published in
3 min readFeb 19, 2018

Playing with animations is always fun but, sometimes, it’s really hard to create them, because you need to do a lot of measurements, calculations and other stuff with the UI. For those reasons, build animations sometimes takes time and a lot of coding.

ConstraintLayout loves ConstraintSet

Today I want to share with you a new way to create awesome animations in your app with just few lines of code (7 lines. YES, SEVEN) using Keyframe Animations with ConstraintLayout and ConstraintSet.

The concept is to create two different layouts, one for the starting point and one for the ending point of the animation. Let’s see first what we’re going to build: Our goal is to create an animation that shows-off the circuit detail when the user press the screen, with seamless and fluid animation.

This animation is created with two different layouts file: circuit.xml and circuit_detail.xml

As you can see, the layouts are exactly the same, the only difference is that in the first one (circuit.xml) the elements are placed offscreen, while in the second one they are in the desired position.

first layout: circuit.xml — The views are the same as the second layout, but they are hidden outside the layout
second layout: circuit_detail.xml — The final view positions

So, let’s build the animation and let’s see how is incredibly easy to make animations with ConstraintLayout and ConstraintSet.

Let the magic happen

First, we need to create a new instance of ConstraintSet, then we can clone the constraints of the second layout (circuit_detail.xml) by calling the clone() method:

val constraintSet = ConstraintSet()
constraintSet.clone(this, R.layout.circuit_detail)

Now, let’s create the transition object used to set the interpolator and the duration of animation:

val transition = ChangeBounds()
transition.interpolator = AnticipateOvershootInterpolator(1.0f)
transition.duration = 1200

And, last but not least, we need to call the TransitionManager.beginDelayedTransition() used to create a new scene and to run the transition on the next rendering frame. Lastly, we call applyTo() to finally start the animation.

TransitionManager.beginDelayedTransition(constraint, transition)

constraintSet.applyTo(constraint)

It’s really 7 lines of code.

That’s it! You can check the full example on my GitHub repo at the following link:

Did you liked the article? Stay in touch and follow me on Twitter (@lpirro93) or write me an email.

--

--

Leonardo Pirro
AndroidPub

Android Developer 🚀 , UX/UI lover, design addicted.