June 9, 2016

ConstraintLayout

One of the Android announcements at Google I/O 2016 was Android Studio 2.2 Preview, which includes the New Layout Editor and Constraint Layout.

ConstraintLayout is a new powerful and flexible Android layout that allows developers to create complex UIs without nesting multiple layouts. It is available in the Android Support Library and compatible with Android 2.3 (Gingerbread) and up. Using the new layout editor, which was built specially for ConstraintLayout will make it easier for developers to build Android UI.

Constraints describe how a view will be positioned relative to other elements in the layout file (another view, layout edge, or invisible guideline). The different types of constraints you can use are side connection with the layout, side connection with a view, side alignment with a view, baseline alignment with a view).

To use ConstraintLayout in your Android project, you should update Android Support Repository to version 32 or higher from the SDK manager, add compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha2' in our Gradle dependencies, and Sync Project with Gradle Files.

Create a new layout by right-clicking your res/layout folder. Select New > Layout resource file. Type "android.support.constraint.ConstraintLayout" as the root element (auto-complete also works so you can type the Con... in the root element). The layout editor will then be displayed.


The New Layout Editor

The Design Mode and Blueprint Mode allows you to view the design mode, blueprint mode, or both. The https://medium.com/@jomartigcal/constraintlayout-b89f135bd537 is used for resizing the view by dragging the corners. Side Constraint Handle specifies the location of the view. The Baseline Constraint Handle aligns text fields' baselines. Constraints are visualized as arrows or lines between views or between a view and the edge of the layout. Autoconnect, when on, automatically calculates the constraints for the view you are adding in the layout. Infer constraints creates constraints for all views in a layout. Show No constraints hides the constraints while Clear Constraints delete them.

Check out the codelab at https://codelabs.developers.google.com/codelabs/constraint-layout to try and learn more about ConstraintLayout. You can also watch the Android Layouts: A New World talk at Google I/O.