How to avoid nested containers inside ConstraintLayout.

Often in the design, there are layouts that look like this:

Most of the developers have no problem to implement this layout, but often when people see a container with a different background color and some nested views inside it, they choose to wrap everything in a LinearLayout/RelativeLayout.

As result we see XML which is using ConstraintLayout as the parent, but not in an efficient way.

But there is a better way!

Have a look! There are 3 nested LinearLayouts inside one simple layout, and two of them have android:layout_weight.

Wrong way, too much-nested LinearLayouts with weights

The problem is that in the same way a complex web page can slow download time, your layout hierarchy if too complex can also cause performance problems.

Using nested instances of LinearLayout can lead to an excessively deep view hierarchy. Furthermore, nesting several instances ofLinearLayout that use the layout_weight parameter can be especially expensive as each child needs to be measured twice. This is particularly important when the layout is inflated repeatedly, such as when used in a ListViewor GridView.

This was one of the reasons why ConstraintLayout was introduced.

There is the way how to replace three LinearLayouts with expensive weights:

Without nested containers

We can just make <View /> with a different background color and constraint it to other views to avoid nesting. Similarly, all nested views can also be extracted from containers with weights and constrained to something.

Whether you constraint to widgets such as ImageView/Button etc you cannot use padding for the <View/> because of that you should use fixed height or wrap these widgets in <FrameLayout/>

This approach is very easy to use, improves layout performance and code readability. Enjoy!

Receive a new Mobile development related stories first. — Hit that follow button
Twitter: @ ChiliLabs
www.chi.lv