How to create a rolling dice animation in Android using MotionLayout

Alessandro Lombardi
3 min readOct 14, 2021

--

This tutorial will cover some basic functionality of MotionLayout, which is a subclass of Android ConstraintLayout that helps to add motion and animation to standard views. Specifically, we are going to build an Android project to simulate the roll of a dice.

First, make sure we have the latest ConstraintLayout dependency in the build.gradle module:

Then, we need to switch from the original Constraint Layout to MotionLayout. In the component tree of main activity layout, right click the default ConstraintLayout and select convert to MotionLayout.

Layout component tree

The activity_main.xml will change to this:

Notice the app:layoutDescription tag: converting to MotionLayout will automatically generate a new activity_main_scene.xml:

XML scene

Inside activity_main.xml we create a text view, set the constraints and choose the dice background among the drawable icons. The dice icons can be found here.

In order to animate, we can either select the Design tab or manually edit the activity_main_scene.xml.

The Design tab will host a UI for editing the scene:

Design tab — Scene Editor

We can set the attributes we want to animate by selecting the end view:

End View — Properties Palette

To simulate a dice roll, rotation about the three axes is set to 360 * 10 degrees, meaning ten complete rotations in two seconds. The amount of time in milliseconds can be set using the duration attribute: click the arrow linking start to end to show the Transition attributes.

Transition attributes

The same result can be achieved by directly editing the activity_main_scene.xml:

Notice how the onClick tag defines what view is responsible for triggering the animation: in this case we select the text view itself.

In order to programmatically add behavior to our animation, in the onCreate of our activity we can add a transition listener to the MotionLayout by implementing the interface MotionLayout.TransitionListener:

For the rolling dice app, add the behavior of randomly choosing a dice face in the override of onTransitionCompleted. For more details, see the full project on GitHub.

Here’s the final result:

Rolling Dice App

--

--