Getting started with ConstraintLayout in Kotlin - Part 1: introduction to ConstraintLayout

Introduction

Introduction

This is the first part of a five-part series. In this series, we will be looking at one of the recently released layouts in Android - the ConstraintLayout. We will cover various building blocks of the layout, how they work collectively, and we will round off the series by creating a complex layout in the final part.

For this first part, however, we will look at the features and the problems the layout attempts to solve. Plus we will set up an Android project, which we will be playing around with through the series.

Prerequisites

For you to follow along in the entire series, you need to have the following requirements:

  • Android Studio (v3.0 or higher) installed on your machine. Download here.
  • Ability to navigate the Android Studio IDE.
  • A basic understanding of Android development, especially layouts.

If you have these prerequisites, let’s start.

The advent of the ConstraintLayout

The ConstraintLayout is a new layout available in the Android Support repository for building flexible and efficient layouts. Unlike preceding layouts, it is not bundled into the support library dependency. This is to enable frequent releases to be shipped easily and so the Android framework releases do not affect them directly.

This layout was introduced in May 2016 during the Google I/O event. The layout comes with higher advantages, better performance, and more flexibility as compared to other layouts. This layout is backward compatible with API 9 (Android 2.3).

The ConstraintLayout system has three parts: constraints, equations, and solver. Constraints are relationships between your views and are determined when you set up your UI. Once you create these relationships, the system will translate them into a linear system of equations. In subsequent parts of this series, we will take a deeper look at constraints.

Based on the constraints you’ve set, the unknowns as to where the views are supposed to be, are resolved. It uses the popular cassowary algorithm to know how to solve the equations (position its constraints). This algorithm is used in other popular platforms too like the AutoLayout in iOS development. The equations go in the solver and it returns the positions, and view sizes to be used in the layout.

The ConstraintLayout becomes very necessary most especially when building complex layouts. Android actually has other layouts, which have their own unique features. Some of which could be used to build complex layouts also. However, they have their own bottlenecks, hence the need to introduce a new layout.

These older layouts have rules that tend to be too rigid. As a result of this, the tendency to nest layouts become higher. For instance, the LinearLayout only permits placing views linearly, either horizontally or vertically. The FrameLayout places views in a stacked manner, the topmost view hides the rest. The RelativeLayout places views relative to each other.

The release of a much more diverse and flexible layout was long overdue.

Bottlenecks of other layouts

One of the major bottlenecks endured in using previous layouts is having a deep view hierarchy. A deep view hierarchy arises when your layout is deeply nested. Deeply nested in the sense that layouts are embedded in other layouts.

A deeply nested layout looks like this:

1<?xml version="1.0" encoding="utf-8"?>
2    <LinearLayout>
3       <LinearLayout>
4           <LinearLayout>
5             <TextView></TextView>       
6           </LinearLayout>
7           <ImageView></ImageView>
8       </LinearLayout>
9       <TextView></TextView>
10       <LinearLayout>
11           <Button></Button>
12       </LinearLayout>
13    </LinearLayout>

In the above sample, we have a parent linear layout that contains a LinearLayout, a TextView, and another LinearLayout.

The first linear layout furthermore contains another LinearLayout, which houses a TextView, and an ImageView. Drawing this layout to the screen by the Android system is actually expensive and bad for performance.

ConstraintLayout comes with a better approach. It actually offers a flatter view hierarchy than the snippet we have above.

If the above layout is converted to a ConstraintLayout, we can have something similar to this:

1<?xml version="1.0" encoding="utf-8"?>
2    <ConstraintLayout>
3       <TextView></TextView>
4       <ImageView></ImageView>
5       <TextView></TextView>
6       <Button></Button>
7    </ConstraintLayout>

Because the view hierarchy here is flat, it means it will take a shorter time to draw the layout, hence, an improved performance over the former. This is one of the major reasons for the advent of ConstraintLayouts.

Layouts are key to the overall user experience of an application and so its performance should be optimized. One layout that looks similar to the ConstraintLayout is the RelativeLayout, which you may have used at some point. They are both powerful layout systems but the ConstraintLayout is a lot more powerful.

It is also worthy to note that they are both smart responsive layouts that scale to most device screens.

Some more interesting features of ConstraintLayout

Apart from the ConstraintLayout giving us a better performance and giving us scalable layouts that fit into multiple screens, there are other interesting features embedded in the layout:

  • Ability to handle GONE views well. GONE views are views that have their visibility set to gone, that is, they are as good as not being part of the layout. Ordinarily, on a RelativeLayout or any other layout, this can distort your design especially when views are relative to each other.

    The ConstraintLayout, however, handles this scenario by adding a dimension of zero to these kinds of views, meaning their constraints are respected and the layout will eventually not be distorted.

  • The ConstraintLayout introduces a new attribute called bias. A bias is a ratio of how the view is placed between its constraints on an axis. This is similar to the weight attribute provided by the LinearLayout. We will look deeper into bias in the next part of the series. By default, the bias is set to 0.5 and it is used for centered constrained elements.

  • The layout also has another feature called chains, which is quite similar to bias. With this, the ConstraintLayout looks to have the dual power of the LinearLayout and RelativeLayout.

  • The ConstraintLayout also offers the ability to perform animations. Recently, a sub-layout under the ConstraintLayout called MotionLayout was released. This is specifically for animations. We will take a look at it in part four of the series.

Setting up our Android project

Going forward, we will be demonstrating how to use ConstraintLayout in our project. For this, we will need to set up a dummy Android project. Launch Android Studio IDE and create a new Android project.

When you open your IDE, you should see something like this:

constraintLayout-1-android-new-project

Select the Start a new Android Studio project option and follow the wizard to setup your project. As usual, your app’s name and package name will be required, along with a minimum SDK of 19. Select an Empty Activity template and wait for Android Studio to build your project.

Since Android Studio 3.0, the ConstraintLayout dependency comes by default when you create a new project. However, if you do not see it, you can add it following the instructions below.

Ensure you have the maven.google.com repository declared in your project-level build.gradle file like this:

1buildscript {
2        repositories {
3            google()
4        }
5        [...]
6    }

Then add the dependency it in the app module build.gradle file like this:

1dependencies {
2        [...]
3        implementation 'com.android.support.constraint:constraint-layout:1.1.2'
4    }

IMPORTANT: If you are already following Android’s new naming conventions as announced here, you should add this instead:

    implementation 'androidx.constraintlayout:constraintlayout:1.1.2'

Be sure to sync your gradle files after adding it to make the library available for use. You are now ready to explore ConstraintLayouts!

You can add ConstraintLayouts to your XML file like this:

1<?xml version="1.0" encoding="utf-8"?>
2    <android.support.constraint.ConstraintLayout 
3      xmlns:android="http://schemas.android.com/apk/res/android"
4      xmlns:app="http://schemas.android.com/apk/res-auto"
5      xmlns:tools="http://schemas.android.com/tools"
6      android:layout_width="match_parent"
7      android:layout_height="match_parent">
8    
9      <!-- Other views go here --!>
10    
11    </android.support.constraint.ConstraintLayout>

Conclusion

In this first part of this series, we have learned that the ConstraintLayout comes in as a better and more efficient layout than other ones. We have also learned how to include it in our app. In subsequent parts, we will delve into deeper ConstraintLayouts.

You can find the repository for this project here.