How to use ConstraintLayout

If you’re familiar with RelativeLayout, then ConstraintLayout should feel similar to you. ConstraintLayout has much more flexibility though, and performs better than the RelativeLayout. In general, you should always use ConstraintLayout over RelativeLayout.

To add ConstraintLayout to your project, place the following in your build.gradle files:

Before we look at an example of ConstraintLayout, let’s look at an example using RelativeLayout. I want to have a layout that looks like this:

Relative Layout

To accomplish this, here is my RelativeLayout:

Now to do the same with ConstraintLayout, I added the same kind of constraints my RelativeLayout had:

But, the result looked like this:
Constraint Layout

This is because my TextView’s width is set to wrap_content, so it only takes as much space as it needs. As opposed to in the RelativeLayout, where the view gets stretched to make it align properly. If you want the view to fill up this space, you can simply set the width to 0dp.

As you can see already, ConstraintLayout can do the same things as RelativeLayout, and more. Another nice addition from ConstraintLayout is the Guideline. This can be used in your ConstraintLayout to help set the position and size of your views. For example, if I wanted TextView1 from my previous example to take up 25% of the width, I could do it like this:

Guideline

One other big improvement over RelativeLayout is the design tab support. While you can write the xml yourself like I did above, there are some nice visual tools available too.
Design tools

Further reading

To learn more about ConstraintLayout, check out the official Android documentation:
https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html

Pierce Zaifman

Android app developer. Hates wasting time and takes satisfaction in improving efficiency in all aspects of life. Also enjoys helping people solve their problems.

London, Ontario, Canada

Subscribe to Pierce Zaifman

Get the latest posts delivered right to your inbox.

or subscribe via RSS.