Wednesday 7 March 2018

Animations with ConstraintLayout and the transition framework

In this post I'd like to share an interesting tutorial published on AndroidPub by Leonardo Pirro:
Build awesome animations with 7 lines of code using ConstraintLayout

You can find a sample app on GitHub here:
sample app in GitHub

The tutorial is about animating layout changes using the android's transition framework with constraints in a ConstraintLayout.
To begin with, let's see a preview of the animation:

preview of the animation

There are some things I would like to point out about this animation...

Layout files

As you can see from the sample app, there are basically 2 layouts: the starting layout (at the beginning of the animation) and the ending layout (at the end of the animation).
The two layouts are almost identical (they have the same widgets), but with different constraints.
For example in the first layout the title and subtitle have the right constraint set on the left of the ImageView, so they are just outside the screen and therefore not visible. This is their starting position at the beginning of the animation.
The same applies to the TextView containing the description. In the first layout it has its top constraint set to the bottom of the ImageView, so it's just outside the screen and therefore not visible.
In the second layout the same widgets are visible because they use different constraints: that's the final position in the animation.

ConstraintSet

This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout.
In the example, using the method clone() we can assign to the ConstraintSet the constraints of the second layout.

Transition framework

The animation makes use of the Android's transition framework. To be more specific, it uses a transition without scenes using the method "beginDelayedTransition" as described here:
Apply a transition without scenes

The sample uses the ChangeBounds transition (move and resize views).

Animation

The animation works as follows:

  1. we retrieve the constraints from the second layout and store them in a ConstraintSet
  2. we define a Transition (ChangeBounds) with an interpolator and execution time
  3. we invoke the method "beginDelayedTransition" to mark the beginning of the animation
  4. we make the changes that must be animated: these simply consist of applying the constraints of the second layout to the first layout
One thing to notice is that the two layouts are identical except for the constraints, which define the position of the widgets. By animating the constraints we can animate the position of the widgets.
Another thing to notice is that the transition is always applied to the first layout (named "constraint"): the first time we apply the constraints of the second layout, the secont time we apply the constraints of the first layout, and so on...