MotionLayout

public class MotionLayout
extends ConstraintLayout

java.lang.Object
   ↳ ViewGroup
     ↳ android.support.constraint.ConstraintLayout
       ↳ android.support.constraint.motion.MotionLayout


A subclass of ConstraintLayout for building animations. Added in 2.0

This Layout supports transitions between constraint sets defined in MotionScenes

A MotionLayout is a ConstraintLayout which allows you to animate layouts between various states.

Note: MotionLayout is available as a support library that you can use on Android systems starting with API level 18 (JellyBean MR2).

MotionLayout links to and requires a MotionScene file. The file contains one top level tag "LayoutDescription"

LayoutDescription

Tags Description
<StateSet> Describes states supported by the system (optional)
<ConstraintSet> Describes a constraint set
<Transition> Describes a transition between two states or ConstraintSets

Transition

Attributes Description
android:id The id of the Transition
constraintSetStart   ConstraintSet to be used as the start constraints or a layout file to get the constraint from
constraintSetEnd ConstraintSet to be used as the end constraints or a layout file to get the constraint from
motionInterpolator The ability to set an overall interpolation (easeInOut, linear, etc.)
duration Length of time to take to perform the transition
staggered float: a quick way to stagger the objects moving
autoTransition automatically transition from one state to another. supports keywords {none, jumpToStart, jumpToEnd, animateToStart, animateToEnd}
<OnSwipe> Adds support for touch handling (optional)
<OnClick> Adds support for triggering transition (optional)
<KeyFrameSet> Describes a set of Key object which modify the animation between constraint sets.

OnSwipe (optional)

Attributes Description
touchAnchorId Have the drag act as if it is moving the "touchAnchorSide" of this object
touchRegionId Limits the region that the touch can be start in to the bounds of this view (even if the view is invisible)
touchAnchorSide The side of the object to move with {top|left|right|bottom}
maxVelocity limit the maximum velocity (in progress/sec) of the animation will on touch up. Default 4
dragDirection which side to swipe from {dragUp|dragDown|dragLeft|dragRight}
maxAcceleration how quickly the animation will accelerate (progress/sec/sec) and decelerate on touch up. Default 1.2
dragScale scale factor to adjust the swipe by. (e.g. 0.5 would require you to move 2x as much)
moveWhenScrollAtTop   If the swipe is scrolling and View (such as RecyclerView or NestedScrollView) do scroll and transition happen at the same time
autoComplete   swipe automatically animates to start or end. Default is true. Warning: turning this off and using time cycles can result in continuous animations.

OnClick (optional)

Attributes Description
motionTarget What view triggers Transition.
clickAction Direction for buttons to move the animation. Or (|) combination of: toggle, transitionToEnd, transitionToStart, jumpToEnd, jumpToStart

StateSet

defaultState  the constraint set or layout to use
<State> The side of the object to move

State

android:id Id of the State
constraints Id of the ConstraintSet or the Layout file
<Variant> a different constraintSet/layout to choose if the with or height matches

Variant

region_widthLessThan match if width less than
region_widthMoreThan match if width more than
region_heightLessThan match if height less than
region_heightMoreThan   match if height more than
constraints Id of the ConstraintSet or layout

ConstraintSet

android:id The id of the ConstraintSet
<Constraint> A ConstraintLayout Constraints + other attributes associated with a view

Constraint

Constraint supports two forms:

1: All of ConstraintLayout + the ones listed below + <CustomAttribute> .

Or

2: Combination of tags: <Layout> <PropertySet> <Transform> <Motion> <CustomAttribute> . The advantage of using these is that if not present the attributes are taken from the base layout file. This saves from replicating all the layout tags if only a Motion tag is needed. If is used then all layout attributes in the base are ignored.

android:id Id of the View
[ConstraintLayout attributes]   Any attribute that is part of ContraintLayout layout is allowed
[Standard View attributes] A collection of view attributes supported by the system (see below)
transitionEasing define an easing curve to be used when animating from this point (e.g. curve(1.0,0,0,1.0)) or key words {standard | accelerate | decelerate | linear }
pathMotionArc the path will move in arc (quarter eclipses) or key words {startVertical | startHorizontal | none }
transitionPathRotate (float) rotate object relative to path taken
drawPath draw the path the layout will animate animate
progress call method setProgress(float) on this view (used to talk to nested ConstraintLayouts etc.)
<CustomAttribute> call a set"name" method via reflection
<Layout> Attributes for the ConstraintLayout e.g. layout_constraintTop_toTopOf
<PropertySet> currently only visibility, alpha, motionProgress,layout_constraintTag.
<Transform> All the view transform API such as android:rotation.
<Motion> Motion Layout control commands such as transitionEasing and pathMotionArc

Layout

[ConstraintLayout attributes] see for attributes

PropertySet

visibility set the Visibility of the view. One of Visible, invisible or gone
alpha setAlpha value
motionProgress   using reflection call setProgress
layout_constraintTag a tagging string to identify the type of object

Transform

android:elevation base z depth of the view.
android:rotation rotation of the view, in degrees.
android:rotationX rotation of the view around the x axis, in degrees.
android:rotationY rotation of the view around the y axis, in degrees.
android:scaleX scale of the view in the x direction
android:scaleY scale of the view in the y direction.
android:translationX translation in x of the view. This value is added post-layout to the left property of the view, which is set by its layout.
android:translationY translation in y of the view. This value is added post-layout to the top property of the view, which is set by its layout
android:translationZ translation in z of the view. This value is added to its elevation.

Motion

transitionEasing Defines an acceleration curve.
pathMotionArc Says the object should move in a quarter ellipse unless the motion is vertical or horizontal
motionPathRotate set the rotation to the path of the object + this angle.
drawPath Debugging utility to draw the motion of the path

CustomAttribute

attributeName The name of the attribute. Case sensitive. ( MyAttr will look for method setMyAttr(...)
customColorValue The value is a color looking setMyAttr(int )
customIntegerValue   The value is an integer looking setMyAttr(int )
customFloatValue The value is a float looking setMyAttr(float )
customStringValue The value is a String looking setMyAttr(String )
customDimension The value is a dimension looking setMyAttr(float )
customBoolean The value is true or false looking setMyAttr(boolean )

KeyFrameSet

This is the container for a collection of Key objects (such as KeyPosition) which provide information about how the views should move

<KeyPosition> Controls the layout position during animation
<KeyAttribute> Controls the post layout properties during animation
<KeyCycle> Controls oscillations with respect to position of post layout properties during animation
<KeyTimeCycle> Controls oscillations with respect to time of post layout properties during animation
<KeyTrigger> trigger callbacks into code at fixed point during the animation

KeyPosition

motionTarget Id of the View or a regular expression to match layout_ConstraintTag
framePosition  The point along the interpolation 0 = start 100 = end
transitionEasing  define an easing curve to be used when animating from this point (e.g. curve(1.0,0,0,1.0)) or key words {standard | accelerate | decelerate | linear }
pathMotionArc The path will move in arc (quarter eclipses) key words {startVertical | startHorizontal | flip | none }
keyPositionType/td> how this keyframe's deviation for linear path is calculated {deltaRelative | pathRelative|parentRelative}
percentX (float) percent distance from start to end along X axis (deltaRelative) or along the path in pathRelative
percentY (float) Percent distance from start to end along Y axis (deltaRelative) or perpendicular to path in pathRelative
percentWidth (float) Percent of change in the width. Note if the width does not change this has no effect.This overrides sizePercent.
percentHeight (float) Percent of change in the width. Note if the width does not change this has no effect.This overrides sizePercent.
curveFit path is traced
drawPath Draw the path of the objects layout takes useful for debugging
sizePercent If the view changes size this controls how growth of the size. (for fixed size objects use KeyAttributes scaleX/X)
curveFit selects a path based on straight lines or a path based on a monotonic spline {linear|spline}

KeyAttribute

motionTarget Id of the View or a regular expression to match layout_ConstraintTag
framePosition  The point along the interpolation 0 = start 100 = end
curveFit selects a path based on straight lines or a path based on a monotonic spline {linear|spline}
transitionEasing Define an easing curve to be used when animating from this point (e.g. curve(1.0,0,0,1.0)) or key words {standard | accelerate | decelerate | linear }
transitionPathRotate (float) rotate object relative to path taken
drawPath draw the path the layout will animate animate
motionProgress call method setProgress(float) on this view (used to talk to nested ConstraintLayouts etc.)
[standard view attributes] A collection of post layout view attributes see below
<CustomAttribute> call a set"name" method via reflection

CustomAttribute

attributeName The name of the attribute. Case sensitive. ( MyAttr will look for method setMyAttr(...)
customColorValue The value is a color looking setMyAttr(int )
customIntegerValue   The value is an integer looking setMyAttr(int )
customFloatValue The value is a float looking setMyAttr(float )
customStringValue The value is a String looking setMyAttr(String )
customDimension The value is a dimension looking setMyAttr(float )
customBoolean The value is true or false looking setMyAttr(boolean )

KeyCycle

motionTarget Id of the View or a regular expression to match layout_ConstraintTag
framePosition   The point along the interpolation 0 = start 100 = end
[Standard View attributes] A collection of view attributes supported by the system (see below)
waveShape The shape of the wave to generate {sin|square|triangle|sawtooth|reverseSawtooth|cos|bounce}
wavePeriod The number of cycles to loop near this region
waveOffset offset value added to the attribute
transitionPathRotate Cycles applied to rotation relative to the path the view is travelling
progress call method setProgress(float) on this view (used to talk to nested ConstraintLayouts etc.)
<CustomAttribute> call a set"name" method via reflection (limited to floats)

CustomAttribute

attributeName The name of the attribute. Case sensitive. ( MyAttr will look for method setMyAttr(...)
customFloatValue The value is a float looking setMyAttr(float )

KeyTimeCycle

motionTarget Id of the View or a regular expression to match layout_ConstraintTag
framePosition   The point along the interpolation 0 = start 100 = end
[Standard View attributes] A collection of view attributes supported by the system (see below)
waveShape The shape of the wave to generate {sin|square|triangle|sawtooth|reverseSawtooth|cos|bounce}
wavePeriod The number of cycles per second
waveOffset offset value added to the attribute
transitionPathRotate Cycles applied to rotation relative to the path the view is travelling
progress call method setProgress(float) on this view (used to talk to nested ConstraintLayouts etc.)
<CustomAttribute> call a set"name" method via reflection (limited to floats)

CustomAttribute

attributeName The name of the attribute. Case sensitive. ( MyAttr will look for method setMyAttr(...)
customFloatValue The value is a float looking setMyAttr(float )

KeyTrigger

motionTarget Id of the View or a regular expression to match layout_ConstraintTag
framePosition  The point along the interpolation 0 = start 100 = end
onCross  (method name) on crossing this position call this methods on the target
onPositiveCross (method name) on forward crossing of the framePosition call this methods on the target
onNegativeCross/td> (method name) backward crossing of the framePosition call this methods on the target
triggerSlack (float) do not call trigger again if the framePosition has not moved this fraction away from the trigger point
triggerId (id) call the TransitionListener with this trigger id
motion_postLayoutCollision Define motion pre or post layout. Post layout is more expensive but captures KeyAttributes or KeyCycle motions.
motion_triggerOnCollision (id) Trigger if the motionTarget collides with the other motionTarget

Standard attributes

android:visibility Android view attribute that
android:alpha Android view attribute that
android:elevation base z depth of the view.
android:rotation rotation of the view, in degrees.
android:rotationX rotation of the view around the x axis, in degrees.
android:rotationY rotation of the view around the y axis, in degrees.
android:scaleX scale of the view in the x direction.
android:scaleY scale of the view in the y direction.
android:translationX  translation in x of the view.
android:translationY  translation in y of the view.
android:translationZ  translation in z of the view.

See also:

Summary

Nested classes

interface MotionLayout.TransitionListener

Added in 2.0

Listener for monitoring events about TransitionLayout. 

Constants

int DEBUG_SHOW_NONE

int DEBUG_SHOW_PATH

int DEBUG_SHOW_PROGRESS

Inherited fields

Public constructors

MotionLayout(Context context)
MotionLayout(Context context, AttributeSet attrs)
MotionLayout(Context context, AttributeSet attrs, int defStyleAttr)

Public methods

void fireTrigger(int triggerId, boolean positive, float progress)

This causes the callback onTransitionTrigger to be called

ConstraintSet getConstraintSet(int id)

Get the ConstraintSet associated with an id

int[] getConstraintSetIds()

Get the id's of all constraintSets used by MotionLayout

int getCurrentState()

Return the current state id

ArrayList<MotionScene.Transition> getDefinedTransitions()

Get all Transitions known to the system.

int getEndState()

Gets the state you are currently transition to.

float getProgress()

Get current position during an animation.

int getStartState()

Gets the state you are currently transitioning from.

float getTargetPosition()

Gets the position you are animating to typically 0 or 1.

long getTransitionTimeMs()

Gets the time of the currently set animation.

void loadLayoutDescription(int motionScene)

This overrides ConstraintLayout and only accepts a MotionScene.

boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed)
boolean onNestedPreFling(View target, float velocityX, float velocityY)
void onNestedPreScroll(View target, int dx, int dy, int[] consumed, int type)
void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type)
void onNestedScrollAccepted(View child, View target, int axes, int type)
boolean onStartNestedScroll(View child, View target, int axes, int type)
void onStopNestedScroll(View target, int type)
boolean onTouchEvent(MotionEvent event)
void rebuildMotion()

This method is deprecated. Please call rebuildScene() instead.

void rebuildScene()

rebuild the motion Layouts

void setInterpolatedProgress(float pos)

Set the transition position between 0 an 1

void setOnHide(float progress)
void setOnShow(float progress)
void setProgress(float pos)

Set the transition position between 0 an 1

void setState(int id, int screenWidth, int screenHeight)

Set the State of the Constraint layout.

void setTransition(int beginId, int endId)

Set a transition explicitly between two constraint sets

void setTransitionDuration(int milliseconds)
void setTransitionListener(MotionLayout.TransitionListener listener)

Set a listener to be notified of drawer events.

void transitionToEnd()

Animate to the ending position

void transitionToStart()

Animate to the starting position

void transitionToState(int id)

Animate to the state defined by the id.

void transitionToState(int id, int screenWidth, int screenHeight)

Animate to the state defined by the id.

Protected methods

void dispatchDraw(Canvas canvas)

Used to draw debugging graphics and to do post layout changes

void onAttachedToWindow()
void onLayout(boolean changed, int left, int top, int right, int bottom)

void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

void parseLayoutDescription(int id)

block ConstraintLayout from handling layout description

void setTransition(MotionScene.Transition transition)

Inherited methods

Constants

DEBUG_SHOW_NONE

public static final int DEBUG_SHOW_NONE

Constant Value: 0 (0x00000000)

DEBUG_SHOW_PATH

public static final int DEBUG_SHOW_PATH

Constant Value: 2 (0x00000002)

DEBUG_SHOW_PROGRESS

public static final int DEBUG_SHOW_PROGRESS

Constant Value: 1 (0x00000001)

Public constructors

MotionLayout

public MotionLayout (Context context)

Parameters
context Context

MotionLayout

public MotionLayout (Context context, 
                AttributeSet attrs)

Parameters
context Context

attrs AttributeSet

MotionLayout

public MotionLayout (Context context, 
                AttributeSet attrs, 
                int defStyleAttr)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

Public methods

fireTrigger

public void fireTrigger (int triggerId, 
                boolean positive, 
                float progress)

This causes the callback onTransitionTrigger to be called

Parameters
triggerId int: The id set set with triggerID

positive boolean: for positive transition edge

progress float: the current progress

getConstraintSet

public ConstraintSet getConstraintSet (int id)

Get the ConstraintSet associated with an id

Returns
ConstraintSet

getConstraintSetIds

public int[] getConstraintSetIds ()

Get the id's of all constraintSets used by MotionLayout

Returns
int[]

getCurrentState

public int getCurrentState ()

Return the current state id

Returns
int current state id

getDefinedTransitions

public ArrayList<MotionScene.Transition> getDefinedTransitions ()

Get all Transitions known to the system.

Returns
ArrayList<MotionScene.Transition>

getEndState

public int getEndState ()

Gets the state you are currently transition to.

Returns
int The State you are transitioning to.

getProgress

public float getProgress ()

Get current position during an animation.

Returns
float current position from 0.0 to 1.0 inclusive

getStartState

public int getStartState ()

Gets the state you are currently transitioning from. If you are transitioning from an unknown state returns -1

Returns
int State you are transitioning from.

getTargetPosition

public float getTargetPosition ()

Gets the position you are animating to typically 0 or 1. This is useful during animation after touch up

Returns
float The target position you are moving to

getTransitionTimeMs

public long getTransitionTimeMs ()

Gets the time of the currently set animation.

Returns
long time in Milliseconds

loadLayoutDescription

public void loadLayoutDescription (int motionScene)

This overrides ConstraintLayout and only accepts a MotionScene.

Parameters
motionScene int: The resource id, or 0 to reset the MotionScene.

onNestedFling

public boolean onNestedFling (View target, 
                float velocityX, 
                float velocityY, 
                boolean consumed)

Parameters
target View

velocityX float

velocityY float

consumed boolean

Returns
boolean

onNestedPreFling

public boolean onNestedPreFling (View target, 
                float velocityX, 
                float velocityY)

Parameters
target View

velocityX float

velocityY float

Returns
boolean

onNestedPreScroll

public void onNestedPreScroll (View target, 
                int dx, 
                int dy, 
                int[] consumed, 
                int type)

Parameters
target View

dx int

dy int

consumed int

type int

onNestedScroll

public void onNestedScroll (View target, 
                int dxConsumed, 
                int dyConsumed, 
                int dxUnconsumed, 
                int dyUnconsumed, 
                int type)

Parameters
target View

dxConsumed int

dyConsumed int

dxUnconsumed int

dyUnconsumed int

type int

onNestedScrollAccepted

public void onNestedScrollAccepted (View child, 
                View target, 
                int axes, 
                int type)

Parameters
child View

target View

axes int

type int

onStartNestedScroll

public boolean onStartNestedScroll (View child, 
                View target, 
                int axes, 
                int type)

Parameters
child View

target View

axes int

type int

Returns
boolean

onStopNestedScroll

public void onStopNestedScroll (View target, 
                int type)

Parameters
target View

type int

onTouchEvent

public boolean onTouchEvent (MotionEvent event)

Parameters
event MotionEvent

Returns
boolean

rebuildMotion

public void rebuildMotion ()

This method is deprecated.
Please call rebuildScene() instead.

rebuild the motion Layouts

rebuildScene

public void rebuildScene ()

rebuild the motion Layouts

setInterpolatedProgress

public void setInterpolatedProgress (float pos)

Set the transition position between 0 an 1

setOnHide

public void setOnHide (float progress)

Parameters
progress float

setOnShow

public void setOnShow (float progress)

Parameters
progress float

setProgress

public void setProgress (float pos)

Set the transition position between 0 an 1

setState

public void setState (int id, 
                int screenWidth, 
                int screenHeight)

Set the State of the Constraint layout. Causing it to load a particular ConstraintSet. for states with variants the vairant with matching width and height constraintSet will be chosen

Parameters
id int: set the state width and height

setTransition

public void setTransition (int beginId, 
                int endId)

Set a transition explicitly between two constraint sets

Parameters
beginId int: the id of the start constraint set

endId int: the id of the end constraint set

setTransitionDuration

public void setTransitionDuration (int milliseconds)

Parameters
milliseconds int

setTransitionListener

public void setTransitionListener (MotionLayout.TransitionListener listener)

Set a listener to be notified of drawer events.

Parameters
listener MotionLayout.TransitionListener: Listener to notify when drawer events occur

transitionToEnd

public void transitionToEnd ()

Animate to the ending position

transitionToStart

public void transitionToStart ()

Animate to the starting position

transitionToState

public void transitionToState (int id)

Animate to the state defined by the id. The id is the id of the ConstraintSet or the id of the State.

Parameters
id int: the state to transition to

transitionToState

public void transitionToState (int id, 
                int screenWidth, 
                int screenHeight)

Animate to the state defined by the id. Width and height may be used in the picking of the id using this StateSet.

Parameters
id int: the state to transition

screenWidth int: the with of the motionLayout used to select the variant

screenHeight int: the height of the motionLayout used to select the variant

Protected methods

dispatchDraw

protected void dispatchDraw (Canvas canvas)

Used to draw debugging graphics and to do post layout changes

onAttachedToWindow

protected void onAttachedToWindow ()

onLayout

protected void onLayout (boolean changed, 
                int left, 
                int top, 
                int right, 
                int bottom)

Parameters
changed boolean

left int

top int

right int

bottom int

onMeasure

protected void onMeasure (int widthMeasureSpec, 
                int heightMeasureSpec)

Parameters
widthMeasureSpec int

heightMeasureSpec int

parseLayoutDescription

protected void parseLayoutDescription (int id)

block ConstraintLayout from handling layout description

setTransition

protected void setTransition (MotionScene.Transition transition)

Parameters
transition MotionScene.Transition