ConstraintLayout


public class ConstraintLayout extends ViewGroup

Known direct subclasses
MotionLayout

A subclass of ConstraintLayout that supports animating between various states Added in 2.0


A ConstraintLayout is a android.view.ViewGroup which allows you to position and size widgets in a flexible way.

Note:ConstraintLayout is available as a support library that you can use on Android systems starting with API level 9 (Gingerbread). As such, we are planning on enriching its API and capabilities over time. This documentation will reflect those changes.

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

Note that you cannot have a circular dependency in constraints.

Also see ConstraintLayout.LayoutParams for layout attributes

Developer Guide

Relative positioning

Relative positioning is one of the basic building blocks 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:

you would need to do:

        <Button android:id="@+id/buttonA" ... />
        <Button android:id="@+id/buttonB" ...
                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.

Here is the list of available constraints:

  • layout_constraintLeft_toLeftOf
  • 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):

        <Button android:id="@+id/buttonB" ...
                app:layout_constraintLeft_toLeftOf="parent" />
        

Margins

If side margins are set, they will be applied to the corresponding constraints (if they exist), 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
  • layout_marginBaseline

Note that a margin can only be positive or equal to zero, and takes a Dimension.

Margins when connected to a GONE widget

When a position constraint target's visibility is View.GONE, you can also indicate a different margin value to be used using the following attributes:

  • layout_goneMarginStart
  • layout_goneMarginEnd
  • layout_goneMarginLeft
  • layout_goneMarginTop
  • layout_goneMarginRight
  • layout_goneMarginBottom
  • layout_goneMarginBaseline

Centering positioning and bias

A useful aspect of ConstraintLayout is in how it deals with "impossible" constraints. For example, if we have something like:

        <androidx.constraintlayout.widget.ConstraintLayout ...>
            <Button android:id="@+id/button" ...
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"/>
        </>
        

Unless the ConstraintLayout happens to have the exact same size as the Button, both constraints cannot be satisfied at the same time (both sides cannot be where we want them to be).

What happens in this case is that the constraints act like opposite forces pulling the widget apart equally; 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

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:

        <androidx.constraintlayout.widget.ConstraintLayout ...>
            <Button android:id="@+id/button" ...
                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. The following attributes can be used:

  • layout_constraintCircle : references another widget id
  • layout_constraintCircleRadius : the distance to the other widget center
  • layout_constraintCircleAngle : which angle the widget should be at (in degrees, from 0 to 360)
 <Button android:id="@+id/buttonA" ... />
 <Button android:id="@+id/buttonB" ...
     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

This specific behavior allows to build layouts where you can temporarily mark widgets as being GONE, without breaking the layout, 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. 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

Minimum dimensions on ConstraintLayout

You can define minimum and maximum sizes for the ConstraintLayout itself:

  • android:minWidth set the minimum width for the layout
  • android:minHeight set the minimum height for the layout
  • android:maxWidth set the maximum width for the layout
  • android:maxHeight set the maximum height for the layout
Those minimum and maximum dimensions will be used by ConstraintLayout when its dimensions are set to WRAP_CONTENT. Widgets dimension constraints

The dimension of the widgets can be specified by setting the android:layout_width and android:layout_height attributes in 3 different ways:

  • Using a specific dimension (either a literal value such as 123dp or a Dimension reference)
  • Using WRAP_CONTENT, which will ask the widget to compute its own size
  • Using 0dp, which is the equivalent of "MATCH_CONSTRAINT"

The first two works in a similar fashion as other layouts. The last one will resize the widget in such a way as matching the constraints that are set. If margins are set, they will be taken in account in the computation.

Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".

WRAP_CONTENT : enforcing constraints (Added in 1.1)

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"
MATCH_CONSTRAINT dimensions (Added in 1.1)

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:

  • layout_constraintWidth_min and layout_constraintHeight_min : will set the minimum size for this dimension
  • layout_constraintWidth_max and layout_constraintHeight_max : will set the maximum size for this dimension
  • layout_constraintWidth_percent and layout_constraintHeight_percent : will set the size of this dimension as a percentage of the parent
Min and Max

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

To use percent, you need to set the following

  • The dimension should be set to MATCH_CONSTRAINT (0dp)
  • The default should be set to percent app:layout_constraintWidth_default="percent" or app:layout_constraintHeight_default="percent"
  • Then set the layout_constraintWidth_percent or layout_constraintHeight_percent attributes to a value between 0 and 1
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.

The ratio can be expressed either as:

  • a float value, representing a ratio between width and height
  • a ratio in the form "width:height"

You can also use ratio if both dimensions are set to MATCH_CONSTRAINT (0dp). In this case the system sets the largest dimensions that satisfies all constraints and maintains the aspect ratio specified. To constrain one specific side based on the dimensions of another, you can pre append W," or H, to constrain the width or height respectively. For example, If one dimension is constrained by two targets (e.g. width is 0dp and centered on parent) you can indicate which side should be constrained, by adding the letter W (for constraining the width) or H (for constraining the height) in front of the ratio, separated by a comma:

          <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 its 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.

Chain heads

Chains are controlled by attributes set on the first element of the chain (the "head" of the chain):

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 into account. In the case of spread chains, margins will be deducted from the allocated space.

Chain Style

When setting the attribute layout_constraintHorizontal_chainStyle or layout_constraintVertical_chainStyle on the first element of a chain, the behavior of the chain will change according to the specified style (default is CHAIN_SPREAD).

  • CHAIN_SPREAD -- the elements will be spread out (default style)
  • Weighted chain -- in CHAIN_SPREAD mode, if some widgets are set to MATCH_CONSTRAINT, they will split the available space
  • CHAIN_SPREAD_INSIDE -- similar, but the endpoints of the chain will not be spread out
  • 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
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 example, 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)

When using margins on elements in a chain, the margins are additive.

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.

Virtual Helper objects

In addition to the intrinsic capabilities detailed previously, you can also use special helper objects in ConstraintLayout to help you with your layout. Currently, the Guideline{@see Guideline} object allows you to create Horizontal and Vertical guidelines which are positioned relative to the ConstraintLayout container. Widgets can then be positioned by constraining them to such guidelines. In 1.1, Barrier and Group were added too.

Optimizer (in 1.1)

In 1.1 we exposed the constraints optimizer. You can decide which optimizations are applied by adding the tag app:layout_optimizationLevel to the ConstraintLayout element.

  • none : no optimizations are applied
  • standard : Default. Optimize direct and barrier constraints only
  • direct : optimize direct constraints
  • barrier : optimize barrier constraints
  • chain : optimize chain constraints (experimental)
  • dimensions : optimize dimensions measures (experimental), reducing the number of measures of match constraints elements

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"

Summary

Nested types

This class contains the different attributes specifying how a view want to be laid out inside a ConstraintLayout.

This is the interface to a valued modifier. implement this and add it using addValueModifier

Constants

static final int
static final String
VERSION = "ConstraintLayout-2.2.0-alpha04"

Public constructors

ConstraintLayout(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)
@TargetApi(value = Build.VERSION_CODES.LOLLIPOP)
ConstraintLayout(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr,
    int defStyleRes
)

Public methods

void

a ValueModify to the ConstraintLayout.

void
void
ConstraintLayout.LayoutParams
Object
getDesignInformation(int type, Object value)
int

The maximum height of this view.

int
int

The minimum height of this view.

int

The minimum width of this view.

int

Return the current optimization level for the layout resolution

String

Returns a JSON5 string useful for debugging the constraints actually applied.

static SharedValues

Returns the SharedValues instance, creating it if it doesn't exist.

View
getViewById(int id)
final ConstraintWidget
void
loadLayoutDescription(int layoutDescription)

Load a layout description file from the resources.

void
void
void
void

Sets a ConstraintSet object to manage constraints.

void
setDesignInformation(int type, Object value1, Object value2)
void
setId(int id)
void
setMaxHeight(int value)

Set the max height for this view

void
setMaxWidth(int value)

Set the max width for this view

void
setMinHeight(int value)

Set the min height for this view

void
setMinWidth(int value)

Set the min width for this view

void
setOnConstraintsChanged(
    ConstraintsChangedListener constraintsChangedListener
)

Notify of constraints changed

void

Set the optimization for the layout resolution.

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

Set the State of the ConstraintLayout, causing it to load a particular ConstraintSet.

boolean

Protected methods

void
applyConstraintsFromLayoutParams(
    boolean isInEditMode,
    View child,
    ConstraintWidget widget,
    ConstraintLayout.LayoutParams layoutParams,
    SparseArray<ConstraintWidget> idToWidget
)
boolean
void
boolean
dynamicUpdateConstraints(int widthMeasureSpec, int heightMeasureSpec)

This can be overridden to change the way Modifiers are used.

ConstraintLayout.LayoutParams
ViewGroup.LayoutParams
boolean
void
onLayout(boolean changed, int left, int top, int right, int bottom)
void
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
void

Subclasses can override the handling of layoutDescription

void
resolveMeasuredDimension(
    int widthMeasureSpec,
    int heightMeasureSpec,
    int measuredWidth,
    int measuredHeight,
    boolean isWidthMeasuredTooSmall,
    boolean isHeightMeasuredTooSmall
)

Handles calling setMeasuredDimension()

void
resolveSystem(
    ConstraintWidgetContainer layout,
    int optimizationLevel,
    int widthMeasureSpec,
    int heightMeasureSpec
)

Handles measuring a layout

void
setSelfDimensionBehaviour(
    ConstraintWidgetContainer layout,
    int widthMode,
    int widthSize,
    int heightMode,
    int heightSize
)

Inherited Constants

From android.view.View
static final int
static final int
static final int
static final int
static final int
static final int
static final Property<ViewFloat>
static final int
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE = "creditCardExpirationDate"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH = "creditCardExpirationMonth"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR = "creditCardExpirationYear"
static final String
static final String
AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode"
static final String
static final String
static final String
static final String
static final String
static final String
static final String
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int[]
static final int[]
static final int[]
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int
GONE = 8
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
KEEP_SCREEN_ON = 67108864
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
NO_ID = -1
static final int
static final int
static final int
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int[]
static final int[]
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final String
VIEW_LOG_TAG = "View"
static final int
static final int[]
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
From android.view.ViewGroup
static final int
static final int
static final int
static final int
static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

Inherited methods

From android.view.View
void
void
void
ViewPropertyAnimator
void
void
boolean
void
void

This method is deprecated.

void
boolean
boolean
boolean
boolean
boolean
canScrollHorizontally(int direction)
boolean
canScrollVertically(int direction)
final void
void
final void
boolean
void
void
static int
combineMeasuredStates(int curState, int newState)
int
int
int
void
WindowInsets
int
int
int
AccessibilityNodeInfo
void
void

This method is deprecated.

boolean
boolean
dispatchNestedFling(float velocityX, float velocityY, boolean consumed)
boolean
dispatchNestedPreFling(float velocityX, float velocityY)
boolean
dispatchNestedPrePerformAccessibilityAction(
    int action,
    Bundle arguments
)
boolean
dispatchNestedPreScroll(
    int dx,
    int dy,
    int[] consumed,
    int[] offsetInWindow
)
boolean
dispatchNestedScroll(
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed,
    int[] offsetInWindow
)
boolean
void
draw(Canvas canvas)
void
drawableHotspotChanged(float x, float y)
final OnBackInvokedDispatcher
final T
<T extends View> findViewById(int id)
final T
<T extends View> findViewWithTag(Object tag)
boolean

This method is deprecated.

void
forceHasOverlappingRendering(boolean hasOverlappingRendering)
void
generateDisplayHash(
    String hashAlgorithm,
    Rect bounds,
    Executor executor,
    DisplayHashResultCallback callback
)
static int
View.AccessibilityDelegate
int
AccessibilityNodeProvider
CharSequence
int
int
String
String
float
Animation
Matrix
IBinder
int[]
Map<IntegerInteger>
String[]
final AutofillId
int
AutofillValue
Drawable
BlendMode
ColorStateList
PorterDuff.Mode
int
final int
float
int
float
Rect
boolean
final boolean
final ContentCaptureSession
CharSequence
final Context
ContextMenu.ContextMenuInfo
final boolean
static int
getDefaultSize(int size, int measureSpec)
Display
final int[]
Bitmap

This method is deprecated.

int

This method is deprecated.

int

This method is deprecated.

void
long
float
int
boolean
boolean
int
ArrayList<View>
getFocusables(int direction)
void
Drawable
int
BlendMode
ColorStateList
PorterDuff.Mode
boolean
getGlobalVisibleRect(Rect r, Point globalOffset)
Handler
float
float
float
float
Runnable
final boolean
final int
void
getHitRect(Rect outRect)
int
int
Drawable
Drawable
int
int
int
int
boolean
KeyEvent.DispatcherState
int
int
int
ViewGroup.LayoutParams
final int
float
int
final boolean
void
getLocationInSurface(int[] location)
void
getLocationInWindow(int[] outLocation)
void
getLocationOnScreen(int[] outLocation)
Matrix
final int
final int
final int
final int
final int
int
int
int
int
int
int
int
int
View.OnFocusChangeListener
int
ViewOutlineProvider
int
int
ViewOverlay
int
int
int
int
int
int
final ViewParent
ViewParent
float
float
PointerIcon
final List<Rect>
String[]
Resources
final boolean
final int
float
int
AttachedSurfaceControl
View
WindowInsets
float
float
float
float
float
int
int
int
int
int
int
final int
final int
int
int
final CharSequence
StateListAnimator
int
int
List<Rect>
int

This method is deprecated.

Object
int
int
CharSequence
final int
float
int
TouchDelegate
ArrayList<View>
float
String
float
float
float
long
int
int
Drawable
Drawable
int
ViewTranslationResponse
ViewTreeObserver
int
final int
int
WindowId
WindowInsetsController
int

This method is deprecated.

IBinder
int
void
float
float
float
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
static View
inflate(Context context, int resource, ViewGroup root)
void

This method is deprecated.

void
void
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean

This method is deprecated.

boolean
boolean
final boolean
final boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
final boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
View
keyboardNavigationClusterSearch(View currentCluster, int direction)
final void
measure(int widthMeasureSpec, int heightMeasureSpec)
static int[]
mergeDrawableStates(int[] baseState, int[] additionalState)
void
offsetLeftAndRight(int offset)
void
offsetTopAndBottom(int offset)
void
void
WindowInsets
void
boolean
boolean
void
void
InputConnection
void
onCreateViewTranslationRequest(
    int[] supportedFormats,
    Consumer<ViewTranslationRequest> requestsCollector
)
void
onCreateVirtualViewTranslationRequests(
    long[] virtualIds,
    int[] supportedFormats,
    Consumer<ViewTranslationRequest> requestsCollector
)
void
onDisplayHint(int hint)
boolean
void
onDraw(Canvas canvas)
void
final void
boolean
void
void
void
onFocusChanged(
    boolean gainFocus,
    int direction,
    Rect previouslyFocusedRect
)
boolean
void
onHoverChanged(boolean hovered)
boolean
void
void
boolean
onKeyDown(int keyCode, KeyEvent event)
boolean
onKeyLongPress(int keyCode, KeyEvent event)
boolean
onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
boolean
onKeyPreIme(int keyCode, KeyEvent event)
boolean
onKeyShortcut(int keyCode, KeyEvent event)
boolean
onKeyUp(int keyCode, KeyEvent event)
void
onOverScrolled(
    int scrollX,
    int scrollY,
    boolean clampedX,
    boolean clampedY
)
void
onPointerCaptureChange(boolean hasCapture)
void
void
onProvideAutofillStructure(ViewStructure structure, int flags)
void
void
void
void
ContentInfo
void
void
onRtlPropertiesChanged(int layoutDirection)
Parcelable
void
onScreenStateChanged(int screenState)
void
onScrollCaptureSearch(
    Rect localVisibleRect,
    Point windowOffset,
    Consumer<ScrollCaptureTarget> targets
)
void
onScrollChanged(int l, int t, int oldl, int oldt)
boolean
onSetAlpha(int alpha)
void
onSizeChanged(int w, int h, int oldw, int oldh)
void
boolean
boolean
void
void
void
onVisibilityAggregated(boolean isVisible)
void
onVisibilityChanged(View changedView, int visibility)
void
onWindowFocusChanged(boolean hasWindowFocus)
void

This method is deprecated.

void
onWindowVisibilityChanged(int visibility)
boolean
overScrollBy(
    int deltaX,
    int deltaY,
    int scrollX,
    int scrollY,
    int scrollRangeX,
    int scrollRangeY,
    int maxOverScrollX,
    int maxOverScrollY,
    boolean isTouchEvent
)
boolean
performAccessibilityAction(int action, Bundle arguments)
boolean
boolean
performContextClick(float x, float y)
boolean
performHapticFeedback(int feedbackConstant)
boolean
ContentInfo
void
playSoundEffect(int soundConstant)
boolean
post(Runnable action)
boolean
postDelayed(Runnable action, long delayMillis)
void
void
postInvalidateDelayed(long delayMilliseconds)
void
void
void
postOnAnimationDelayed(Runnable action, long delayMillis)
void
void
boolean
void
void
void
void
void

This method is deprecated.

final boolean
void
boolean
final void
final T
<T extends View> requireViewById(int id)
void
static int
resolveSize(int size, int measureSpec)
static int
resolveSizeAndState(int size, int measureSpec, int childMeasuredState)
void
final void
saveAttributeDataForStyleable(
    Context context,
    int[] styleable,
    AttributeSet attrs,
    TypedArray t,
    int defStyleAttr,
    int defStyleRes
)
void
void
scheduleDrawable(Drawable who, Runnable what, long when)
void
scrollBy(int x, int y)
void
scrollTo(int x, int y)
void
sendAccessibilityEvent(int eventType)
void
void
setAccessibilityDataSensitive(int accessibilityDataSensitive)
void
void
setAccessibilityHeading(boolean isHeading)
void
void
setAccessibilityPaneTitle(CharSequence accessibilityPaneTitle)
void
void
void
setActivated(boolean activated)
void
setAllowClickWhenDisabled(boolean clickableWhenDisabled)
void
void
void
setAlpha(float alpha)
void
void
void
setAutoHandwritingEnabled(boolean enabled)
void
setAutofillHints(String[] autofillHints)
void
void
setBackground(Drawable background)
void
setBackgroundColor(int color)
void

This method is deprecated.

void
void
void
void
final void
setBottom(int bottom)
void
setCameraDistance(float distance)
void
setClickable(boolean clickable)
void
setClipBounds(Rect clipBounds)
void
setClipToOutline(boolean clipToOutline)
void
void
setContentDescription(CharSequence contentDescription)
void
setContextClickable(boolean contextClickable)
void
setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled)
void

This method is deprecated.

void
setDrawingCacheEnabled(boolean enabled)

This method is deprecated.

void

This method is deprecated.

void
void
setElevation(float elevation)
void
setEnabled(boolean enabled)
void
setFadingEdgeLength(int length)
void
void
setFitsSystemWindows(boolean fitSystemWindows)
void
setFocusable(boolean focusable)
void
setFocusableInTouchMode(boolean focusableInTouchMode)
void
setFocusedByDefault(boolean isFocusedByDefault)
void
setForceDarkAllowed(boolean allow)
void
setForeground(Drawable foreground)
void
setForegroundGravity(int gravity)
void
void
void
void
setHandwritingBoundsOffsets(
    float offsetLeft,
    float offsetTop,
    float offsetRight,
    float offsetBottom
)
void
void
setHapticFeedbackEnabled(boolean hapticFeedbackEnabled)
void
setHasTransientState(boolean hasTransientState)
void
setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled)
void
setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled)
void
void
void
setHovered(boolean hovered)
void
void
void
void
setIsCredential(boolean isCredential)
void
setIsHandwritingDelegate(boolean isHandwritingDelegate)
void
setKeepScreenOn(boolean keepScreenOn)
void
setKeyboardNavigationCluster(boolean isCluster)
void
setLabelFor(int id)
void
void
setLayerType(int layerType, Paint paint)
void
setLayoutDirection(int layoutDirection)
void
final void
setLeft(int left)
final void
setLeftTopRightBottom(int left, int top, int right, int bottom)
void
setLongClickable(boolean longClickable)
final void
setMeasuredDimension(int measuredWidth, int measuredHeight)
void
setMinimumHeight(int minHeight)
void
setMinimumWidth(int minWidth)
void
setNestedScrollingEnabled(boolean enabled)
void
setNextClusterForwardId(int nextClusterForwardId)
void
setNextFocusDownId(int nextFocusDownId)
void
setNextFocusForwardId(int nextFocusForwardId)
void
setNextFocusLeftId(int nextFocusLeftId)
void
setNextFocusRightId(int nextFocusRightId)
void
setNextFocusUpId(int nextFocusUpId)
void
void
void
void
void
void
void
void
void
void
void
void
setOnReceiveContentListener(
    String[] mimeTypes,
    OnReceiveContentListener listener
)
void
void

This method is deprecated.

void
void
void
void
void
setOverScrollMode(int overScrollMode)
void
setPadding(int left, int top, int right, int bottom)
void
setPaddingRelative(int start, int top, int end, int bottom)
void
setPivotX(float pivotX)
void
setPivotY(float pivotY)
void
final void
setPreferKeepClear(boolean preferKeepClear)
final void
void
setPressed(boolean pressed)
void
final void
setRevealOnFocusHint(boolean revealOnFocus)
final void
setRight(int right)
void
setRotation(float rotation)
void
setRotationX(float rotationX)
void
setRotationY(float rotationY)
void
setSaveEnabled(boolean enabled)
void
setSaveFromParentEnabled(boolean enabled)
void
setScaleX(float scaleX)
void
setScaleY(float scaleY)
void
setScreenReaderFocusable(boolean screenReaderFocusable)
void
setScrollBarDefaultDelayBeforeFade(
    int scrollBarDefaultDelayBeforeFade
)
void
setScrollBarFadeDuration(int scrollBarFadeDuration)
void
setScrollBarSize(int scrollBarSize)
void
setScrollBarStyle(int style)
final void
void
void
setScrollContainer(boolean isScrollContainer)
void
setScrollIndicators(int indicators)
void
setScrollX(int value)
void
setScrollY(int value)
void
setScrollbarFadingEnabled(boolean fadeScrollbars)
void
setSelected(boolean selected)
void
setSoundEffectsEnabled(boolean soundEffectsEnabled)
void
void
void
void
setSystemUiVisibility(int visibility)

This method is deprecated.

void
void
setTextAlignment(int textAlignment)
void
setTextDirection(int textDirection)
void
final void
setTop(int top)
void
void
setTransitionAlpha(float alpha)
final void
setTransitionName(String transitionName)
void
setTransitionVisibility(int visibility)
void
setTranslationX(float translationX)
void
setTranslationY(float translationY)
void
setTranslationZ(float translationZ)
void
setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled)
void
setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled)
void
void
void
void
void
setVisibility(int visibility)
void
setWillNotCacheDrawing(boolean willNotCacheDrawing)

This method is deprecated.

void
setWillNotDraw(boolean willNotDraw)
void
setX(float x)
void
setY(float y)
void
setZ(float z)
boolean
ActionMode
void
final boolean
startDrag(
    ClipData data,
    View.DragShadowBuilder shadowBuilder,
    Object myLocalState,
    int flags
)

This method is deprecated.

final boolean
startDragAndDrop(
    ClipData data,
    View.DragShadowBuilder shadowBuilder,
    Object myLocalState,
    int flags
)
boolean
void
String
void
void
void
final void
boolean
boolean

This method is deprecated.

boolean
From android.view.ViewGroup
void
void
addExtraDataToAccessibilityNodeInfo(
    AccessibilityNodeInfo info,
    String extraDataKey,
    Bundle arguments
)
void
addFocusables(ArrayList<View> views, int direction, int focusableMode)
void
boolean
void
void
addView(View child)
boolean
addViewInLayout(View child, int index, ViewGroup.LayoutParams params)
void
attachLayoutAnimationParameters(
    View child,
    ViewGroup.LayoutParams params,
    int index,
    int count
)
void
attachViewToParent(View child, int index, ViewGroup.LayoutParams params)
void
boolean
void
void
childHasTransientStateChanged(
    View child,
    boolean childHasTransientState
)
void
void
void
void
void
debug(int depth)
void
void
void
detachViewsFromParent(int start, int count)
WindowInsets
boolean
void
void
dispatchCreateViewTranslationRequest(
    Map<AutofillId, long[]> viewIds,
    int[] supportedFormats,
    TranslationCapability capability,
    List<ViewTranslationRequest> requests
)
void
boolean
void
dispatchDrawableHotspotChanged(float x, float y)
void
void
boolean
boolean
boolean
boolean
boolean
boolean
void
dispatchPointerCaptureChanged(boolean hasCapture)
void
void
void
void
void
dispatchScrollCaptureSearch(
    Rect localVisibleRect,
    Point windowOffset,
    Consumer<ScrollCaptureTarget> targets
)
void
dispatchSetActivated(boolean activated)
void
dispatchSetPressed(boolean pressed)
void
dispatchSetSelected(boolean selected)
void
void

This method is deprecated.

void
boolean
boolean
boolean
dispatchUnhandledMove(View focused, int direction)
void
dispatchVisibilityChanged(View changedView, int visibility)
void
dispatchWindowFocusChanged(boolean hasFocus)
void
void
WindowInsets
WindowInsetsAnimation.Bounds
void

This method is deprecated.

void
boolean
drawChild(Canvas canvas, View child, long drawingTime)
void
void
View
OnBackInvokedDispatcher
void
findViewsWithText(
    ArrayList<View> outViews,
    CharSequence text,
    int flags
)
View
focusSearch(View focused, int direction)
void
boolean
CharSequence
View
getChildAt(int index)
int
int
getChildDrawingOrder(int childCount, int drawingPosition)
static int
getChildMeasureSpec(int spec, int padding, int childDimension)
boolean
boolean
getChildVisibleRect(View child, Rect r, Point offset)
boolean
boolean
int
View
LayoutAnimationController
Animation.AnimationListener
int
LayoutTransition
int
ViewGroupOverlay
int

This method is deprecated.

boolean
boolean
boolean
int
final void
invalidateChild(View child, Rect dirty)

This method is deprecated.

ViewParent
invalidateChildInParent(int[] location, Rect dirty)

This method is deprecated.

boolean

This method is deprecated.

boolean

This method is deprecated.

boolean
boolean

This method is deprecated.

boolean
boolean
boolean
void
final void
layout(int l, int t, int r, int b)
void
measureChild(
    View child,
    int parentWidthMeasureSpec,
    int parentHeightMeasureSpec
)
void
measureChildWithMargins(
    View child,
    int parentWidthMeasureSpec,
    int widthUsed,
    int parentHeightMeasureSpec,
    int heightUsed
)
void
measureChildren(int widthMeasureSpec, int heightMeasureSpec)
void
notifySubtreeAccessibilityStateChanged(
    View child,
    View source,
    int changeType
)
final void
final void
void
int[]
onCreateDrawableState(int extraSpace)
void
void
boolean
boolean
boolean
onNestedFling(
    View target,
    float velocityX,
    float velocityY,
    boolean consumed
)
boolean
onNestedPreFling(View target, float velocityX, float velocityY)
boolean
onNestedPrePerformAccessibilityAction(
    View target,
    int action,
    Bundle args
)
void
onNestedPreScroll(View target, int dx, int dy, int[] consumed)
void
onNestedScroll(
    View target,
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed
)
void
onNestedScrollAccepted(View child, View target, int axes)
boolean
onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)
boolean
PointerIcon
onResolvePointerIcon(MotionEvent event, int pointerIndex)
boolean
onStartNestedScroll(View child, View target, int nestedScrollAxes)
void
void
void
void
void
removeDetachedView(View child, boolean animate)
void
void
removeViewAt(int index)
void
void
removeViews(int start, int count)
void
removeViewsInLayout(int start, int count)
void
requestChildFocus(View child, View focused)
boolean
requestChildRectangleOnScreen(
    View child,
    Rect rectangle,
    boolean immediate
)
void
requestDisallowInterceptTouchEvent(boolean disallowIntercept)
boolean
requestFocus(int direction, Rect previouslyFocusedRect)
boolean
void
boolean
void
void
setAddStatesFromChildren(boolean addsStates)
void

This method is deprecated.

void
setAnimationCacheEnabled(boolean enabled)

This method is deprecated.

void

This method is deprecated.

void
void

This method is deprecated.

void
setClipChildren(boolean clipChildren)
void
setClipToPadding(boolean clipToPadding)
void
setDescendantFocusability(int focusability)
void
void
void
setLayoutMode(int layoutMode)
void
void
void
void
setPersistentDrawingCache(int drawingCacheToKeep)

This method is deprecated.

void
void
setTouchscreenBlocksFocus(boolean touchscreenBlocksFocus)
void
setTransitionGroup(boolean isTransitionGroup)
void
boolean
ActionMode
startActionModeForChild(
    View originalView,
    ActionMode.Callback callback
)
void
void
void
suppressLayout(boolean suppress)
void

Constants

DESIGN_INFO_ID

Added in 2.2.0
public static final int DESIGN_INFO_ID = 0

VERSION

Added in 2.2.0
public static final String VERSION = "ConstraintLayout-2.2.0-alpha04"

Protected fields

mConstraintLayoutSpec

Added in 2.2.0
protected ConstraintLayoutStates mConstraintLayoutSpec

mDirtyHierarchy

Added in 2.2.0
protected boolean mDirtyHierarchy

mLayoutWidget

Added in 2.2.0
protected ConstraintWidgetContainer mLayoutWidget

Public constructors

ConstraintLayout

Added in 2.2.0
public ConstraintLayout(@NonNull Context context)

ConstraintLayout

Added in 2.2.0
public ConstraintLayout(@NonNull Context context, @Nullable AttributeSet attrs)

ConstraintLayout

Added in 2.2.0
public ConstraintLayout(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)

ConstraintLayout

Added in 2.2.0
@TargetApi(value = Build.VERSION_CODES.LOLLIPOP)
public ConstraintLayout(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr,
    int defStyleRes
)

Public methods

addValueModifier

Added in 2.2.0
public void addValueModifier(ConstraintLayout.ValueModifier modifier)

a ValueModify to the ConstraintLayout. This can be useful to add custom behavour to the ConstraintLayout or address limitation of the capabilities of Constraint Layout

Parameters
ConstraintLayout.ValueModifier modifier

fillMetrics

Added in 2.2.0
public void fillMetrics(Metrics metrics)
Parameters
Metrics metrics

Fills metrics object

forceLayout

public void forceLayout()

generateLayoutParams

Added in 2.2.0
public ConstraintLayout.LayoutParams generateLayoutParams(AttributeSet attrs)

getDesignInformation

Added in 2.2.0
public Object getDesignInformation(int type, Object value)

getMaxHeight

Added in 2.2.0
public int getMaxHeight()

The maximum height of this view.

Returns
int

The maximum height of this view

See also
setMaxHeight

getMaxWidth

Added in 2.2.0
public int getMaxWidth()

getMinHeight

Added in 2.2.0
public int getMinHeight()

The minimum height of this view.

Returns
int

The minimum height of this view

See also
setMinHeight

getMinWidth

Added in 2.2.0
public int getMinWidth()

The minimum width of this view.

Returns
int

The minimum width of this view

See also
setMinWidth

getOptimizationLevel

Added in 2.2.0
public int getOptimizationLevel()

Return the current optimization level for the layout resolution

Returns
int

the current level

getSceneString

Added in 2.2.0
public String getSceneString()

Returns a JSON5 string useful for debugging the constraints actually applied. In situations where a complex set of code dynamically constructs constraints it is useful to be able to query the layout for what are the constraints.

Returns
String

json5 string representing the constraint in effect now.

getSharedValues

Added in 2.2.0
public static SharedValues getSharedValues()

Returns the SharedValues instance, creating it if it doesn't exist.

Returns
SharedValues

the SharedValues instance

getViewById

Added in 2.2.0
public View getViewById(int id)
Parameters
int id

the view id

Returns
View

the child view, can return null Return a direct child view by its id if it exists

getViewWidget

Added in 2.2.0
public final ConstraintWidget getViewWidget(View view)
Parameters
View view

loadLayoutDescription

Added in 2.2.0
public void loadLayoutDescription(int layoutDescription)

Load a layout description file from the resources.

Parameters
int layoutDescription

The resource id, or 0 to reset the layout description.

onViewAdded

public void onViewAdded(View view)

onViewRemoved

public void onViewRemoved(View view)

requestLayout

public void requestLayout()

setConstraintSet

Added in 2.2.0
public void setConstraintSet(ConstraintSet set)

Sets a ConstraintSet object to manage constraints. The ConstraintSet overrides LayoutParams of child views.

Parameters
ConstraintSet set

Layout children using ConstraintSet

setDesignInformation

Added in 2.2.0
public void setDesignInformation(int type, Object value1, Object value2)

setId

public void setId(int id)

setMaxHeight

Added in 2.2.0
public void setMaxHeight(int value)

Set the max height for this view

Parameters
int value

setMaxWidth

Added in 2.2.0
public void setMaxWidth(int value)

Set the max width for this view

Parameters
int value

setMinHeight

Added in 2.2.0
public void setMinHeight(int value)

Set the min height for this view

Parameters
int value

setMinWidth

Added in 2.2.0
public void setMinWidth(int value)

Set the min width for this view

Parameters
int value

setOnConstraintsChanged

Added in 2.2.0
public void setOnConstraintsChanged(
    ConstraintsChangedListener constraintsChangedListener
)

Notify of constraints changed

Parameters
ConstraintsChangedListener constraintsChangedListener

setOptimizationLevel

Added in 2.2.0
public 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
int level

optimization level

setState

Added in 2.2.0
public void setState(int id, int screenWidth, int screenHeight)

Set the State of the ConstraintLayout, causing it to load a particular ConstraintSet. For states with variants the variant with matching width and height constraintSet will be chosen

Parameters
int id

the constraint set state

int screenWidth

the width of the screen in pixels

int screenHeight

the height of the screen in pixels

shouldDelayChildPressedState

public boolean shouldDelayChildPressedState()
Returns
boolean

Protected methods

applyConstraintsFromLayoutParams

Added in 2.2.0
protected void applyConstraintsFromLayoutParams(
    boolean isInEditMode,
    View child,
    ConstraintWidget widget,
    ConstraintLayout.LayoutParams layoutParams,
    SparseArray<ConstraintWidget> idToWidget
)

checkLayoutParams

protected boolean checkLayoutParams(ViewGroup.LayoutParams p)

dispatchDraw

protected void dispatchDraw(Canvas canvas)

dynamicUpdateConstraints

Added in 2.2.0
protected boolean dynamicUpdateConstraints(int widthMeasureSpec, int heightMeasureSpec)

This can be overridden to change the way Modifiers are used.

Parameters
int widthMeasureSpec
int heightMeasureSpec
Returns
boolean

generateDefaultLayoutParams

Added in 2.2.0
protected ConstraintLayout.LayoutParams generateDefaultLayoutParams()

isRtl

Added in 2.2.0
protected boolean isRtl()

onLayout

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

onMeasure

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

parseLayoutDescription

Added in 2.2.0
protected void parseLayoutDescription(int id)

Subclasses can override the handling of layoutDescription

Parameters
int id

resolveMeasuredDimension

Added in 2.2.0
protected void resolveMeasuredDimension(
    int widthMeasureSpec,
    int heightMeasureSpec,
    int measuredWidth,
    int measuredHeight,
    boolean isWidthMeasuredTooSmall,
    boolean isHeightMeasuredTooSmall
)

Handles calling setMeasuredDimension()

Parameters
int widthMeasureSpec
int heightMeasureSpec
int measuredWidth
int measuredHeight
boolean isWidthMeasuredTooSmall
boolean isHeightMeasuredTooSmall

resolveSystem

Added in 2.2.0
protected void resolveSystem(
    ConstraintWidgetContainer layout,
    int optimizationLevel,
    int widthMeasureSpec,
    int heightMeasureSpec
)

Handles measuring a layout

Parameters
ConstraintWidgetContainer layout
int optimizationLevel
int widthMeasureSpec
int heightMeasureSpec

setSelfDimensionBehaviour

Added in 2.2.0
protected void setSelfDimensionBehaviour(
    ConstraintWidgetContainer layout,
    int widthMode,
    int widthSize,
    int heightMode,
    int heightSize
)