tezvyn:

MotionLayout: Animate Layouts with States, Not Code

AI-drafted, machine-checkedSource: developer.android.comadvanced

MotionLayout animates layouts by describing start and end states in XML, letting the system handle the transition. Use it for complex UI choreography, like a collapsing toolbar, or to link animation progress to a user's swipe.

WHY IT EXISTS Traditional Android animation frameworks required writing imperative code, which could become complex and hard to maintain for intricate UI choreography. MotionLayout was created to provide a declarative way to describe animations, separating the what (the visual change) from the how (the code that executes it).

THE MENTAL MODEL Think of MotionLayout as a state machine for your UI's appearance. You define different layout states in XML files called ConstraintSets. Then, you define transitions between these states in a separate XML file called a MotionScene. The system handles the interpolation, animating all view properties smoothly from one state to another.

HOW IT WORKS MotionLayout is a subclass of ConstraintLayout. It's controlled by a MotionScene XML file that you associate with it. This scene file contains one or more Transitions. Each Transition specifies a start ConstraintSet, an end ConstraintSet, and the triggers or drivers for the animation. The animation can be started by an event like a click, or its progress can be tied directly to user input, like a swipe gesture, allowing for fully interactive, scrubbable animations.

WHEN TO USE IT Use MotionLayout for complex, multi-element animations that need to be coordinated. It excels at things like collapsing toolbars, parallax scrolling effects, complex drawer animations, and any UI where you want the animation progress to be directly controlled by a user's gesture. It's for showpiece moments in your UI.

WHEN NOT TO USE IT Avoid MotionLayout for simple, one-off animations on a single view, such as a button's press effect or a view fading in. The standard ViewPropertyAnimator or ObjectAnimator APIs are simpler and more lightweight for these tasks. Using MotionLayout for simple cases adds unnecessary complexity and overhead.

ONE CANONICAL EXAMPLE A YouTube-style video player where swiping down on the video shrinks it into a mini-player in the corner of the screen. This is a perfect use case. The "fullscreen" and "mini-player" layouts are two ConstraintSets, and the transition between them is driven by the user's vertical swipe gesture.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.