If you’re just starting your adventure with ConstraintLayout, the new layout that’s available in a support library and is closely integrated with the visual UI editor in Android Studio 2.2.
What is ConstraintLayout in Android?
A ConstraintLayout in Android 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).
In this article I’d like to highlight recent additions to ConstraintLayout in Android Studio 2.3 (Beta): chains and ratios, as well as give some general ConstraintLayout tips and tricks.
Creating chains is a new feature that lets you position views along a single axis (horizontal or vertical), that conceptually is a bit similar to a LinearLayout. As implemented by ConstraintLayout in Android, a chain is a series of views which are linked via bi-directional connections.
To create a chain in the layout editor, select the views you wish to chain together, right click on one of the views and click on “Center views horizontally” (or “Center views vertically”).
This creates the necessary connections for you. Moreover, a new button appears when you select any of the chain elements. It lets you toggle between three chain modes: Spread, Spread Inside, and Packed Chain.
There are two additional techniques you can use when dealing with chains:
Recommended article on Layout:
- Fan Layout Manager for Android
- Android SpaceTabLayout Animation
- Android AdaptiveTableLayout CSV Library
- Android Circular Layout Manager
- AwesomeLayoutManager Android Layout Library
- Two Panels Layout Animation Android Library
If you have a Spread or Spread Inside chain and any views in the chain have their size set to MATCH_CONSTRAINT (or “0dp”), the remaining space in the chain will be distributed among them according to weights defined in layout_constraintHorizontal_weight or layout_constraintVertical_weight.
If you have a Packed chain, you can adjust the horizontal (or vertical) bias to move all elements of the chain left and right (or up and down).
Ratios let you accomplish roughly the same thing as a PercentFrameLayout, i.e. restrict a View to a set width to height ratio, without the overhead of the additional ViewGroup in your hierarchy.
To set a ratio for any view inside a ConstraintLayout:
- Make sure at least one of the size constraints is dynamic, i.e. not “Fixed” and not “Wrap Content”.
- Click the “Toggle aspect ratio constraint” that appears in the top left corner of the box.
- Input the desired aspect ratio in width:height format, for example: 16:9
Full article >>: Building UI with ConstraintLayout in Android?