Android: ConstraintLayout

Joshua U
3 min readApr 25, 2022

--

ConstraintLayout is a layout manager for Android which allows you to position and size widgets in a flexible way. It’s available for both the Android view system and Jetpack Compose.

  • It is recommended default layout for Android.
  • It solves costly issue of too many nested layouts, while allowing complex behavior.
  • Position and size views within it using a set of constraints.

What is Constraint ?

A restriction or limitation on the properties of a view that the layout attempts to respect.

Simple ConstraintLayout Example:

<androidx.constraintlayout.widget.ConstraintLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"><TextView...app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
ConstraintLayout Example

Constraint Widget in Layout Editor :

Constraint Widget
Fixed
Wrap content
Match constraints

CASE 1: Wrap content for width and height :

wrap content for width and height

CASE 2: Wrap content for width, fixed height :

wrap content for width, fixed height

CASE 3: Center a view horizontally:

center a view horizontally

CASE 4: Use match_constraint:

We can’t use match_parent on a child view, use match_constraint instead.

Use match_constraint

Chains:

Chains let us position views in relation to each other and they can be linked horizontally or vertically. Chains provide much of LinearLayout functionality.

Create a Chain in Layout Editor:

Step 1: Select the objects you want to be in the chain.

Step-2: Right-click and select Chains.

Step-3: Create a horizontal or vertical chain.

Example on creating chains

Chain Styles:

Different chain styles

References:

https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout

--

--

Joshua U

Python Enthusiast, Assistant Professor, Care for developing