Build awesome animations with 7 lines of code using ConstraintLayout
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
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.
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.
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
val constraintSet = ConstraintSet()
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.
It’s really 7 lines of code.
That’s it! You can check the full example on my GitHub repo at the following link: