Tutorial

Android ConstraintLayout Example Tutorial

Published on August 3, 2022
author

Anupam Chugh

Android ConstraintLayout Example Tutorial

In this tutorial, we’ll discuss the intricacies of android ConstraintLayout. Google had introduced android constraint layout editor at Google I/O Conference 2016. The new Layout Editor has a set of powerful tools to allow developers to create flat-ui hierarchies for their complex layouts.

Android ConstraintLayout

To use android ConstraintLayout, make sure you’re using the latest Android Studio version. Ideally, Android Studio 2.2 and above. We need to download the necessary SDK Tools for ConstraintLayout from the SDK Manager. android constraintlayout Create a new empty activity project and add the following dependency inside the build.gradle file. compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4' Create a new layout with the root class set to ConstraintLayout as shown in the image below. android constraint layout To convert an old layout into a ConstraintLayout. Open the design pane of the respective layout, right click the root component and choose the relevant option as shown in the image below. android constraint layout

Android Constraint Layout Overview

Android ConstraintLayout is used to define a layout by assigning constraints for every child view/widget relative to other views present. A ConstraintLayout is similar to a RelativeLayout, but with more power. The aim of ConstraintLayout is to improve the performance of the applications by removing the nested views with a flat and flexible design. A view inside the ConstraintLayout has handles(or anchor points) on each side which are used to assign the constraints. Let’s drag and drop a TextView on the layout and assign the constraints to it. Android ConstraintLayout textview The TextView above has three types of handles:

Resize handle - It’s present on the four corners and is used to resize the view, but keeping its constraints intact. Side handle - It’s the circular handle present on the centre of each side. It’s used to set the top, left, bottom and right constraints of the view. Baseline handle - It’s used to align the baseline with another textview in the layout.

Let’s assign the constraints on the TextView and look into the xml code of it. Android ConstraintLayout example Notice the Properties inspector pane at the right-hand side: Android ConstraintLayout textview properties It shows the margins set for each side of the view. It also allows to change the size of the view by toggling between the following modes:

  • Wrap Content - This wraps the view to fill it’s content. Android ConstraintLayout wrap
  • Any Size - This is similar to match parent. Android ConstraintLayout any size
  • Fixed Size - This allows us to set constant width and height. Android ConstraintLayout fixed mode

The xml code for the above layout looks like: sample.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="16dp" />
</android.support.constraint.ConstraintLayout>
  • app:layout_constraintLeft_toLeftOf="parent" - constraintLeft is the anchor point to the left of the view. toLeftOf signifies aligning the view to the left of the assigned view which is “parent” in this case. When the absolute positions are set on the view, the xml properties that are used are -
tools:layout_editor_absoluteY="48dp"
tools:layout_editor_absoluteX="40dp"

Let’s add another TextView and align their baselines. Android ConstraintLayout tutorial The xml code for the above layout is :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        app:layout_constraintBaseline_toBaselineOf="@+id/textView"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp"
        app:layout_constraintRight_toLeftOf="@+id/textView"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp" />

</android.support.constraint.ConstraintLayout>

There are two other tools Auto-connect and Inferences that are used to created constraints automatically.

  1. Auto-Connect - This feature can be enabled by clicking:Android ConstraintLayout example As the name suggests, Auto-connect creates constraints automatically between two neighbouring views
  2. Inference - This feature is enabled by clicking:Android ConstraintLayout example tutorial The Inference engine creates constraints among all elements in a layout. The inference engine tries to find and create optimal connections based on various factors such as the positions of the widgets and their size.

A demo of Auto-Connect layout is given below: Android ConstraintLayout auto connect As you can see in the above gif, The constraints are animated automatically. Notice the horizontal and vertical sliders in the properties pane. They are called horizontal and vertical bias respectively. They allow us to position a view along the horizontal or vertical axis using a bias value, this will be relative to it’s constrained position. The xml code for the above demo is given below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/ic_launcher"
        android:id="@+id/imageView7"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.58000004"
        app:layout_constraintHorizontal_bias="0.47" />
</android.support.constraint.ConstraintLayout>

Demo of a layout with Inference enabled is given below: Android ConstraintLayout inferences The xml code for the above gif is :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView22"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintLeft_creator="1"
        android:layout_marginBottom="59dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        android:layout_marginEnd="31dp"
        app:layout_constraintRight_toRightOf="@+id/textView22"
        android:layout_marginTop="178dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginRight="31dp" />
</android.support.constraint.ConstraintLayout>

tools:layout_constraintTop_creator="1": The creator attributes to keep track of who created the constraints, particularly if they are created by the inference engine they’re assigned as 1.

Deleting Constraints

To delete an individual constraint, hover over the circular handle and click it has it turns red. To delete all constraints of a view, click the symbol underneath it that looks like: Android ConstraintLayout delete A sample demo gif is given below: Android Constraint Layout delete This brings an end to this tutorial. You can go ahead and try replacing some of your own layouts with a constraint layout.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
December 23, 2019

Is it right app:layout_constraintRight_toLeftOf=“@+id/textView”? or should it be like app:layout_constraintLeft_toRightOf=“@+id/textView”

- Vishal

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 5, 2018

    Best example and explanation i’ve seen. I’ve had issues getting everthing positioned correctly in a complex layout with relative layout. This example helps.

    - Philip G Gibbs

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 17, 2017

      Hi Khushbu, People should slowly start using Constraint Layouts in their projects. Reason: It has all the features you need to avoid nesting your layouts. Nested Layouts can impact the performance of your application badly. Thanks

      - Anupam Chugh

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 17, 2017

        Hi Anupam, Superb detailed explanation. Really enjoy learning all ur tutorials. Hey but do ppl use constraint layout? I mean I feel it will take time to get comfortable with it. Bcz normally all codding can be done without using it right? Thanks for gr8 explanation on constraint layout along with demo

        - khushbu

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Featured on Community

          Get our biweekly newsletter

          Sign up for Infrastructure as a Newsletter.

          Hollie's Hub for Good

          Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

          Become a contributor

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          Welcome to the developer cloud

          DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

          Learn more