ConstraintLayout is an Android layout known as a view group, which acts as a container for laying out UI elements. It uses constraints to build large and complex layouts, while maintaining a flat hierarchy of views.
In this context, a view group is a group of views that form a layout, where individual views are the various UI elements available (e.g.
Button), and the constraints dictate the relationships between these elements. It is available to developers as part of the Android Jetpack suite.
Android developers have a choice of several view groups when laying out views. You should use the most appropriate for the layout you are creating.
ConstraintLayout is the recommended choice for building responsive layouts with complex arrangements of views.
The concept of adding individual constraints to views allows for flexibility with view layout, while the flat view hierarchy of a
ConstraintLayout prevents reduced performance caused by nesting multiple view groups.
Depending on your requirements, other view groups might be more appropriate:
LinearLayout- use this when your views can be arranged into a vertical or horizontal list with a single direction, and a single child view per row of the list.
RelativeLayout- use this when you want to position views relative to each other and maintain a flat view hierarchy, but also need to support older applications prior to API level 9.
RelativeLayoutis less performant and has less tooling support than
ConstraintLayoutshould be preferred for applications starting with API level 9 onwards.
To arrange views within a
ConstraintLayout, each view should be given at least one horizontal and one vertical constraint, which defines the view position along the respective horizontal and vertical axis. Android Studio boasts a collection of useful tooling around constraints for working with minimal friction, allowing users to build layouts entirely through drag-and-dropping, but the same results can be achieved by directly editing the XML. In the example code below, we see an example of a
TextView that is constrained horizontally between a guideline and the parent view, and vertically by the height of an
- Quick and easy to build a responsive UI.
- Eliminates the need for nested view groups, keeping your layout in a flat hierarchy.
- More flexible than simple linear layouts.
- Has more built in tools and better performance than relative layouts.
- Can be difficult to manage as complexity grows over time. With such layouts, there is a trade off between nested hierarchies and the difficulty of maintaining complex constraints.
- Drag-and-drop functionality is not practical for a complex UI with views constrained close together. In this case the layout should be built by editing the XML directly.
- Overkill for a minimal UI that could be built with linear layouts.