Constraint Layout
Constraint Layout
There are currently various types of constraints that you can use:
Relative positioning
Margins
Centering positioning
Circular positioning
Visibility behavior
Dimension constraints
Chains
Virtual Helpers objects
Optimizer
Developer Guide
Relative positioning
Relative positioning is one of the basic building block of creating layouts in ConstraintLayout. Those
constraints allow you to position a given widget relative to another one. You can constrain a widget
on the horizontal and vertical axis:
Horizontal Axis: left, right, start and end sides
Vertical Axis: top, bottom sides and text baseline
The general concept is to constrain a given side of a widget to another side of any other widget.
For example, in order to position button B to the right of button A (Fig. 1):
Fig. 1 - Relative Positioning Example
app:layout_constraintLeft_toRightOf="@+id/buttonA" />
This tells the system that we want the left side of button B to be constrained to the right side of
button A. Such a position constraint means that the system will try to have both sides share the
same location.
Fig. 2 - Relative Positioning Constraints
layout_constraintLeft_toRightOf
layout_constraintRight_toLeftOf
layout_constraintRight_toRightOf
layout_constraintTop_toTopOf
layout_constraintTop_toBottomOf
layout_constraintBottom_toTopOf
layout_constraintBottom_toBottomOf
layout_constraintBaseline_toBaselineOf
layout_constraintStart_toEndOf
layout_constraintStart_toStartOf
layout_constraintEnd_toStartOf
layout_constraintEnd_toEndOf
They all take a reference id to another widget, or the parent (which will reference the parent
container, i.e. the ConstraintLayout):
app:layout_constraintLeft_toLeftOf="parent" />
Margins
Fig. 3 - Relative Positioning Margins
If side margins are set, they will be applied to the corresponding constraints (if they exist) (Fig. 3),
enforcing the margin as a space between the target and the source side. The usual layout margin
attributes can be used to this effect:
android:layout_marginStart
android:layout_marginEnd
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom
Note that a margin can only be positive or equals to zero, and takes a Dimension.
layout_goneMarginStart
layout_goneMarginEnd
layout_goneMarginLeft
layout_goneMarginTop
layout_goneMarginRight
layout_goneMarginBottom
<android.support.constraint.ConstraintLayout ...>
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent/>
</>
What happens in this case is that the constraints act like opposite forces pulling the widget apart
equally (Fig. 4); such that the widget will end up being centered in the parent container. This will
apply similarly for vertical constraints.
Bias
The default when encountering such opposite constraints is to center the widget; but you can tweak
the positioning to favor one side over another using the bias attributes:
layout_constraintHorizontal_bias
layout_constraintVertical_bias
Fig. 5 - Centering Positioning with Bias
For example the following will make the left side with a 30% bias instead of the default 50%, such
that the left side will be shorter, with the widget leaning more toward the left side (Fig. 5):
<android.support.constraint.ConstraintLayout ...>
app:layout_constraintHorizontal_bias="0.3"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent/>
</>
Using bias, you can craft User Interfaces that will better adapt to screen sizes changes.
Circular positioning (Added in 1.1)
You can constrain a widget center relative to another widget center, at an angle and a distance. This
allows you to position a widget on a circle (see Fig. 6). The following attributes can be used:
Fig. 6 - Circular Positioning
<Button android:id="@+id/buttonA" ... />
app:layout_constraintCircle="@+id/buttonA"
app:layout_constraintCircleRadius="100dp"
app:layout_constraintCircleAngle="45" />
Visibility behavior
ConstraintLayout has a specific handling of widgets being marked as View.GONE.
GONE widgets, as usual, are not going to be displayed and are not part of the layout itself (i.e. their
actual dimensions will not be changed if marked as GONE).
But in terms of the layout computations, GONE widgets are still part of it, with an important distinction:
For the layout pass, their dimension will be considered as zero (basically, they will be
resolved to a point)
If they have constraints to other widgets they will still be respected, but any margins will be
as if equals to zero
Fig. 7 - Visibility Behavior
This specific behavior allows to build layouts where you can temporarily mark widgets as
being GONE, without breaking the layout (Fig. 7), which can be particularly useful when doing simple
layout animations.
Note: The margin used will be the margin that B had defined when connecting to A (see Fig. 7 for an
example). In some cases, this might not be the margin you want (e.g. A had a 100dp margin to the
side of its container, B only a 16dp to A, marking A as gone, B will have a margin of 16dp to the
container). For this reason, you can specify an alternate margin value to be used when the
connection is to a widget being marked as gone (see the section above about the gone margin
attributes).
Dimensions constraints
If a dimension is set to WRAP_CONTENT, in versions before 1.1 they will be treated as a literal
dimension -- meaning, constraints will not limit the resulting dimension. While in general this is
enough (and faster), in some situations, you might want to use WRAP_CONTENT, yet keep enforcing
constraints to limit the resulting dimension. In that case, you can add one of the corresponding
attribute:
app:layout_constrainedWidth=”true|false”
app:layout_constrainedHeight=”true|false”
When a dimension is set to MATCH_CONSTRAINT, the default behavior is to have the resulting size
take all the available space. Several additional modifiers are available:
The value indicated for min and max can be either a dimension in Dp, or "wrap", which will use the
same value as what WRAP_CONTENT would do.
Percent dimension
Ratio
You can also define one dimension of a widget as a ratio of the other one. In order to do that, you
need to have at least one constrained dimension be set to 0dp (i.e., MATCH_CONSTRAINT), and set the
attribute layout_constraintDimensionRatio to a given ratio. For example:
<Button android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1" />
will set the height of the button to be the same as its width.
<Button android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="H,16:9"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
will set the height of the button following a 16:9 ratio, while the width of the button will match the
constraints to parent.
Chains
Chains provide group-like behavior in a single axis (horizontally or vertically). The other axis can be
constrained independently.
Creating a chain
A set of widgets are considered a chain if they are linked together via a bi-directional connection
(see Fig. 9, showing a minimal chain, with two widgets).
Fig. 9 - Chain
Chain heads
Chains are controlled by attributes set on the first element of the chain (the "head" of the chain):
Fig. 10 - Chain Head
The head is the left-most widget for horizontal chains, and the top-most widget for vertical chains.
Margins in chains
If margins are specified on connections, they will be taken in account. In the case of spread chains,
margins will be deducted from the allocated space.
Chain Style
CHAIN_PACKED -- the elements of the chain will be packed together. The horizontal or vertical
bias attribute of the child will then affect the positioning of the packed elements
Fig. 11 - Chains Styles
Weighted chains
The default behavior of a chain is to spread the elements equally in the available space. If one or
more elements are using MATCH_CONSTRAINT, they will use the available empty space (equally
divided among themselves). The
attribute layout_constraintHorizontal_weight and layout_constraintVertical_weight will
control how the space will be distributed among the elements using MATCH_CONSTRAINT. For
exemple, on a chain containing two elements using MATCH_CONSTRAINT, with the first element using
a weight of 2 and the second a weight of 1, the space occupied by the first element will be twice that
of the second element.
Margins and chains (in 1.1)
For example, on a horizontal chain, if one element defines a right margin of 10dp and the next
element defines a left margin of 5dp, the resulting margin between those two elements is 15dp.
An item plus its margins are considered together when calculating leftover space used by chains to
position items. The leftover space does not contain the margins.
This attribute is a mask, so you can decide to turn on or off specific optimizations by listing the ones
you want. For example: app:layout_optimizationLevel="direct|barrier|chain"
See also:
Guideline
Summary
Nested classes
class ConstraintLayout.LayoutParams
This class contains the different attributes specifying how a view want to be laid out
inside a ConstraintLayout.
Inherited constants
From class android.view.ViewGroup
From class android.view.View
Inherited fields
From class android.view.View
Public constructors
ConstraintLayout(Context context)
ConstraintLayout(Context context, AttributeSet attrs)
ConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr)
Public methods
int getMaxHeight()
int getMaxWidth()
int getMinHeight()
int getMinWidth()
int getOptimizationLevel()
void requestLayout()
void setConstraintSet(ConstraintSet set)
Protected methods
boolean checkLayoutParams(ViewGroup.LayoutParams p)
ConstraintLayout.LayoutPara generateDefaultLayoutParams()
ms
ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams
p)
Inherited methods
From class android.view.ViewGroup
From class android.view.View
From class java.lang.Object
From interface android.view.ViewParent
From interface android.view.ViewManager
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.accessibility.AccessibilityEventSource
Public constructors
ConstraintLayout
ConstraintLayout (Context context)
Parameters
context Context
ConstraintLayout
ConstraintLayout (Context context,
AttributeSet attrs)
Parameters
context Context
attrs AttributeSet
ConstraintLayout
ConstraintLayout (Context context,
AttributeSet attrs,
int defStyleAttr)
Parameters
context Context
attrs AttributeSet
defStyleAttr int
Public methods
getMaxHeight
int getMaxHeight ()
Returns
See also:
setMaxHeight(int)
getMaxWidth
int getMaxWidth ()
Returns
int
getMinHeight
int getMinHeight ()
Returns
See also:
setMinHeight(int)
getMinWidth
int getMinWidth ()
Returns
setMinWidth(int)
getOptimizationLevel
int getOptimizationLevel ()
Returns
requestLayout
void requestLayout ()
setConstraintSet
void setConstraintSet (ConstraintSet set)
Parameters
setMaxHeight
void setMaxHeight (int value)
Set the max height for this view
setMaxWidth
void setMaxWidth (int value)
setMinHeight
void setMinHeight (int value)
setMinWidth
void setMinWidth (int value)
setOptimizationLevel
void setOptimizationLevel (int level)
Set the optimization for the layout resolution. The optimization can be any of the
following:
Optimizer.OPTIMIZATION_NONE
Optimizer.OPTIMIZATION_STANDARD
a mask composed of specific optimizations
The mask can be composed of any combination of the following:
Optimizer.OPTIMIZATION_DIRECT
Optimizer.OPTIMIZATION_BARRIER
Optimizer.OPTIMIZATION_CHAIN (experimental)
Optimizer.OPTIMIZATION_DIMENSIONS (experimental)
Note that the current implementation of Optimizer.OPTIMIZATION_STANDARD is as a
mask of DIRECT and BARRIER.
Parameters
Protected methods
checkLayoutParams
boolean checkLayoutParams (ViewGroup.LayoutParams p)
Parameters
p ViewGroup.LayoutParams
Returns
boolean
generateDefaultLayoutParams
ConstraintLayout.LayoutParams generateDefaultLayoutParams ()
Returns
ConstraintLayout.LayoutParams
generateLayoutParams
ViewGroup.LayoutParams generateLayoutParams (ViewGroup.LayoutParams p)
Parameters
p ViewGroup.LayoutParams
Returns
ViewGroup.LayoutParams
onLayout
void onLayout (boolean changed,
int left,
int top,
int right,
int bottom)
Parameters
changed boolean
left int
top int
right int
bottom int
onMeasure
void onMeasure (int widthMeasureSpec,
int heightMeasureSpec)
Parameters
widthMeasureSpec int
heightMeasureSpec int
LAYOUT PARAMS
ConstraintLayout.LayoutParams
public static class ConstraintLayout.LayoutParams
extends ViewGroup.MarginLayoutParams
java.lang.Object
↳ android.view.ViewGroup.LayoutParams
↳ android.view.ViewGroup.MarginLayoutParams
↳ android.support.constraint.ConstraintLayout.LayoutParams
This class contains the different attributes specifying how a view want to be laid out
inside a ConstraintLayout. For building up constraints at run time, using ConstraintSet is
recommended.
Summary
Constants
int BASELINE
int BOTTOM
The bottom side of a view.
int END
int LEFT
int MATCH_CONSTRAINT
int PARENT_ID
int RIGHT
int START
int TOP
int UNSET
Inherited constants
From class android.view.ViewGroup.LayoutParams
Fields
public CHAIN_PACKED
static
final int Chain packed style
public CHAIN_SPREAD
static
final int Chain spread style
public CHAIN_SPREAD_INSIDE
static
final int Chain spread inside style
public HORIZONTAL
static
final int The horizontal orientation.
public MATCH_CONSTRAINT_PERCENT
static
final int Set matchConstraintDefault* percent to be based on a percent of another
dimension (by default, the parent) Use to set the matchConstraintDefaultWidth
and matchConstraintDefaultHeight
public MATCH_CONSTRAINT_SPREAD
static
final int Set matchConstraintDefault* spread as much as possible within its constraints.
public MATCH_CONSTRAINT_WRAP
static
final int Set matchConstraintDefault* default to the wrap content size.
public VERTICAL
static
final int The vertical orientation.
Constrains the baseline of a child to the baseline of a target child (contains the
target child id).
Constrains the bottom side of a child to the bottom side of a target child
(contains the target child id).
Constrains the bottom side of a child to the top side of a target child (contains
the target child id).
public circleAngle
float
The angle used for a circular constraint]
Constrains the center of a child to the center of a target child (contains the target
child id).
public constrainedHeight
boolean
Specify if the vertical dimension is constrained in case both top & bottom
constraints are set and the widget dimension is not a fixed dimension.
public constrainedWidth
boolean
Specify if the horizontal dimension is constrained in case both left & right
constraints are set and the widget dimension is not a fixed dimension.
public String dimensionRatio
Constrains the end side of a child to the end side of a target child (contains the
target child id).
Constrains the end side of a child to the start side of a target child (contains the
target child id).
The distance of child (guideline) to the top or left edge of its parent.
The distance of child (guideline) to the top or left edge of its parent.
public guidePercent
float
The ratio of the distance to the parent's sides
public helped
boolean
public horizontalBias
float
The ratio between two connections when the left and right (or start and end)
sides are constrained.
If the child is the start of a horizontal chain, this attribute will drive how the
elements of the chain will be positioned.
public horizontalWeight
float
The child's weight that we can use to distribute the available horizontal space in
a chain, if the dimension behaviour is set to MATCH_CONSTRAINT
Constrains the left side of a child to the left side of a target child (contains the
target child id).
Constrains the left side of a child to the right side of a target child (contains the
target child id).
-- the default.
-- the default.
public matchConstraintPercentHeight
float
Specify the percentage when using the match constraint percent mode.
public matchConstraintPercentWidth
float
Specify the percentage when using the match constraint percent mode.
Constrains the right side of a child to the left side of a target child (contains the
target child id).
Constrains the right side of a child to the right side of a target child (contains the
target child id).
Constrains the start side of a child to the end side of a target child (contains the
target child id).
Constrains the start side of a child to the start side of a target child (contains the
target child id).
Constrains the top side of a child to the bottom side of a target child (contains
the target child id).
Constrains the top side of a child to the top side of a target child (contains the
target child id).
public verticalBias
float
The ratio between two connections when the top and bottom sides are
constrained.
If the child is the start of a vertical chain, this attribute will drive how the
elements of the chain will be positioned.
public verticalWeight
float
The child's weight that we can use to distribute the available vertical space in a
chain, if the dimension behaviour is set to MATCH_CONSTRAINT
Inherited fields
From class android.view.ViewGroup.MarginLayoutParams
From class android.view.ViewGroup.LayoutParams
Public constructors
ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams sourc
e)
ConstraintLayout.LayoutParams(Context c, AttributeSet attrs)
ConstraintLayout.LayoutParams(ViewGroup.LayoutParams source)
Public methods
void reset()
void resolveLayoutDirection(in
t layoutDirection)
void validate()
Inherited methods
From class android.view.ViewGroup.MarginLayoutParams
From class android.view.ViewGroup.LayoutParams
From class java.lang.Object