Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the new Android Constraint Layout to reduce View hierarchy

Do you have any idea on how to use the new Constraint Layout that was recently announced at this year's Google I/O?

like image 240
Bogdan M. Avatar asked May 19 '16 08:05

Bogdan M.


People also ask

Which layout is best for large complex hierarchies in Android?

Consider using flatter layouts such as RelativeLayout or GridLayout to improve performance.

What is the use of constraint layout in Android?

A ConstraintLayout is a ViewGroup which allows you to position and size widgets in a flexible way. Note: ConstraintLayout is available as a support library that you can use on Android systems starting with API level 9 (Gingerbread).

Which has better performance LinearLayout or RelativeLayout?

And it can go worse if Nested Relative Layout is used, the already twice measured child of inner Relative Layout would be again measured twice by outer Relative Layout which becomes 4 times just for one view! So Linear Layout should preferred over Relative Layout!

Which is better ConstraintLayout and RelativeLayout?

If you have the choice start with ConstraintLayout, but if you already have your app in RelativeLayout, stay with it. That's all I have been following. RelativeLayout is very limited in functionality and many complex layouts can't be made using it, especially when ratios are involved.


2 Answers

You can go to an existing layout resource file, open the visual editor and right-click on a RelativeLayout (for example) and click the option to convert to a constraint layout.

You also have to add the Gradle dependency in build.gradle file:

compile 'com.android.support.constraint:constraint-layout:1.0.0' 
like image 84
Adrian Olar Avatar answered Oct 13 '22 22:10

Adrian Olar


From Docs

If you're updating an existing project, proceed as follows:

Ensure you have the latest Android Support Repository (version 32 or higher): // This was the part that was missing for me

Click Tools > Android > SDK Manager. Click the SDK Tools tab. Select Android Support Repository, then click OK.

Add the updated Constraint Layout library as a dependency in your build.gradle file:

dependencies {   compile 'com.android.support.constraint:constraint-layout:1.0.0' } 

In the toolbar or sync notification, click Sync Project with Gradle Files.

To add a new constraint layout to your project:

  • Right-click on your module's layout directory, then click New > XML > Layout XML. Enter a name for the layout and enter "android.support.constraint.ConstraintLayout" for the Root Tag. Click Finish.

To convert an existing layout to a constraint layout:

  • Open your existing layout in Android Studio and select the Design tab at the bottom of the editor window. In the Component Tree window, right-click the layout and click Convert to ConstraintLayout.
like image 45
Mikelis Kaneps Avatar answered Oct 13 '22 23:10

Mikelis Kaneps