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
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
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.
To learn more about ConstraintLayout, check out the official Android documentation: