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:

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:

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:

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.

Further reading

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

If You Want To Read More Like This, Follow Me On Medium. Thanks!

Originally published at piercezaifman.com on August 24, 2017.

Freelance Android app developer | I love productivity, creativity, and finding balance | Email me for a quote at pierce@piercezaifman.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store