Using ConstraintLayout in Android Studio

As mentioned more than once in previous chapters, Google has made significant changes to the Android Studio Layout Editor tool, many of which were made solely to support user interface layout design using ConstraintLayout. Now that the basic concepts of ConstraintLayout have been outlined in the previous chapter, this chapter will explore these concepts in more detail while also outlining how the Layout Editor tool allows ConstraintLayout-based user interfaces to be designed and implemented.

Design and Layout Views

The chapter entitled A Guide to the Android Studio Layout Editor Tool explained that the Android Studio Layout Editor tool provides two ways to view the user interface layout of an activity in the form of Design and

Layout (also known as blueprint) views. These views of the layout may be displayed individually or, as in Figure 26-1, side-by-side:

Figure 26-1

The Design view (positioned on the left in the above figure) presents a “what you see is what you get” representation of the layout, wherein the layout appears as it will within the running app. On the other hand, the Layout view displays a blueprint style of view where shaded outlines represent the widgets. As shown in Figure 26-1 above, the Layout view also displays the constraint connections (in this case, opposing constraints used to center a button within the layout). These constraints are also overlaid onto the Design view when a specific widget in the layout is selected or when the mouse pointer hovers over the design area, as illustrated in Figure 26-2:

Figure 26-2

The appearance of constraint connections in both views can be changed using the View Options menu shown in Figure 26-3:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 26-3

In addition to the two modes of displaying the user interface layout, the Layout Editor tool provides three ways of establishing the constraints required for a specific layout design.

Autoconnect Mode

Autoconnect, as the name suggests, automatically establishes constraint connections as items are added to the layout. Autoconnect mode may be turned on and off using the toolbar button indicated in Figure 26-4:

Figure 26-4

Autoconnect mode uses algorithms to decide the best constraints to establish based on the widget’s position and the widget’s proximity to both the sides of the parent layout and other elements. If any of the automatic constraint connections fail to provide the desired behavior, these may be changed manually, as outlined later in this chapter.

Inference Mode

Inference mode uses a heuristic approach involving algorithms and probabilities to automatically implement constraint connections after widgets have already been added to the layout. This mode is usually used when the Autoconnect feature has been turned off, and objects have been added to the layout without any constraint connections. This allows the layout to be designed by dragging and dropping objects from the palette onto the layout canvas and making size and positioning changes until the layout appears as required. Essentially, this involves “painting” the layout without worrying about constraints. Inference mode may also be used during the design process to fill in missing constraints within a layout.

Constraints are automatically added to a layout when the Infer constraints button (Figure 26-5) is clicked:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 26-5

As with Autoconnect mode, there is always the possibility that the Layout Editor tool will infer incorrect constraints, though these may be modified and corrected manually.

Manipulating Constraints Manually

The third option for implementing constraint connections is to do so manually. When doing so, it will be helpful to understand the various handles that appear around a widget within the Layout Editor tool. Consider, for example, the widget shown in Figure 26-6:

Figure 26-6

The spring-like lines (A) represent established constraint connections leading from the sides of the widget to the targets. The small square markers (B) in each corner of the object are resizing handles which, when clicked and dragged, serve to resize the widget. The small circle handles (C) located on each side of the widget are the side constraint anchors. To create a constraint connection, click on the handle and drag the resulting line to the element to which the constraint is to be connected (such as a guideline or the side of either the parent layout or another widget), as outlined in Figure 26-7. When connecting to the side of another widget, drag the line to the side constraint handle of that widget and release the line when the widget and handle are highlighted:

Figure 26-7

If the constraint line is dragged to a widget and released but not attached to a constraint handle, the layout editor will display a menu containing a list of the sides to which the constraint may be attached. In Figure 26-8, for example, the constraint can be attached to the top or bottom edge of the destination button widget:

Figure 26-8

An additional marker indicates the anchor point for baseline constraints whereby the content within the widget (as opposed to outside edges) is used as the alignment point. To display this marker, right-click on the widget and select the Show Baseline menu option. To establish a constraint connection from a baseline constraint handle, hover the mouse pointer over the handle until it highlights before clicking and dragging to the target (such as the baseline anchor of another widget, as shown in Figure 26-9).

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 26-9

To hide the baseline anchors, right-click on the widget again and select the Hide Baseline menu option.

Adding Constraints in the Inspector

Constraints may also be added to a view within the Android Studio Layout Editor tool using the Inspector panel in the Attributes tool window, as shown in Figure 26-10. The square in the center represents the currently selected view, and the areas around the square the constraints, if any, applied to the corresponding sides of the view:

Figure 26-10

The absence of a constraint on the side of the view is represented by a dotted line leading to a blue circle containing a plus sign (as is the case with the view’s bottom edge in the above figure). To add a constraint, click on this blue circle, and the layout editor will add a constraint connected to what it considers the most appropriate target within the layout.

Viewing Constraints in the Attributes Window

A list of constraints configured on the currently selected widget can be viewed by displaying the Constraints section of the Attributes tool window, as shown in Figure 26-11 below:

Figure 26-11

Clicking on a constraint in the list will select that constraint within the design layout.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Deleting Constraints

To delete an individual constraint, select the constraint either within the design layout or the Attributes tool window so that it highlights (in Figure 26-12, for example, the right-most constraint has been selected) and tap the keyboard delete key. The constraint will then be removed from the layout.

Figure 26-12

Another option is to hover the mouse pointer over the constraint anchor while holding down the Ctrl (Cmd on macOS) key and clicking on the anchor after it turns red:

Figure 26-13

Alternatively, remove all of the constraints on a widget by right-clicking on it and selecting the Clear Constraints of Selection menu option.

To remove all of the constraints from every widget in a layout, use the toolbar button highlighted in Figure 26-14:

Figure 26-14

Adjusting Constraint Bias

The previous chapter outlined the concept of using bias settings to favor one opposing constraint over another. Bias within the Android Studio Layout Editor tool is adjusted using the Inspector located in the Attributes tool window and shown in Figure 26-15. The two sliders indicated by the arrows in the figure are used to control the bias of the currently selected widget’s vertical and horizontal opposing constraints.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 26-15

Understanding ConstraintLayout Margins

Constraints can be used with margins to implement fixed gaps between a widget and another element (such as another widget, a guideline, or the side of the parent layout). Consider, for example, the horizontal constraints applied to the Button object in Figure 26-16:

Figure 26-16

As currently configured, horizontal constraints run to the left and right edges of the parent ConstraintLayout. As such, the widget has opposing horizontal constraints indicating that the ConstraintLayout layout engine has some discretion in terms of the actual positioning of the widget at runtime. This allows the layout some flexibility to accommodate different screen sizes and device orientations. The horizontal bias setting can also control the widget’s position right up to the right-hand side of the layout. Figure 26-17, for example, shows the same button with 100% horizontal bias applied:

Figure 26-17

ConstraintLayout margins can appear at the end of constraint connections and represent a fixed gap into which the widget cannot be moved, even when adjusting bias or responding to layout changes elsewhere in the activity. In Figure 26-18, the right-hand constraint now includes a 50dp margin into which the widget cannot be moved even though the bias is still set at 100%.

Figure 26-18

Existing margin values on a widget can be modified from within the Inspector. As shown in Figure 26-19, a drop-down menu is being used to change the right-hand margin on the currently selected widget to 16dp. Alternatively, clicking on the current value also allows a number to be typed into the field.

Figure 26-19

The default margin for new constraints can be changed at any time using the option in the toolbar highlighted in Figure 26-20:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 26-20

The Importance of Opposing Constraints and Bias

As discussed in the previous chapter, opposing constraints, margins, and bias form the cornerstone of responsive layout design in Android when using the ConstraintLayout. When a widget is constrained without opposing constraint connections, those constraints are essentially margin constraints. This is indicated visually within the Layout Editor tool by solid straight lines accompanied by margin measurements, as shown in Figure 26-21.

Figure 26-21

The above constraints fix the widget at that position. The result is that if the device is rotated to landscape orientation, the widget will no longer be visible since the vertical constraint pushes it beyond the top edge of the device screen (as is the case in Figure 26-22). A similar problem will arise if the app is run on a device with a smaller screen than that used during the design process.

Figure 26-22

When opposing constraints are implemented, the constraint connection is represented by the jagged spring-like line (the spring metaphor is intended to indicate that the position of the widget is not fixed to absolute X and Y coordinates):

Figure 26-23

In the above layout, vertical and horizontal bias settings have been configured such that the widget will always be positioned 90% of the distance from the bottom and 35% from the left-hand edge of the parent layout. When rotated, therefore, the widget is still visible and positioned in the same location relative to the dimensions of the screen:

Figure 26-24

When designing a responsive and adaptable user interface layout, it is important to consider bias and opposing constraints when manually designing a user interface layout and correcting automatically created constraints.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Configuring Widget Dimensions

The inner dimensions of a widget within a ConstraintLayout can also be configured using the Inspector. As outlined in the previous chapter, widget dimensions can be set to wrap content, fixed, or match constraint modes. The prevailing settings for each dimension on the currently selected widget are shown within the square representing the widget in the Inspector, as illustrated in Figure 26-25:

Figure 26-25

The above figure sets the horizontal and vertical dimensions to wrap content mode (indicated by the inward-pointing chevrons). The inspector uses the following visual indicators to represent the three dimension modes:

Fixed Size

Match Constraint

Wrap Content

Table 26-1

To change the current setting, click on the indicator to cycle through the three settings.

In addition, a widget’s size can be expanded horizontally or vertically to the maximum amount allowed by the constraints and other widgets in the layout using the Expand Horizontally and Expand Vertically options. These are accessible by right-clicking on a widget within the layout and selecting the Organize option from the resulting menu (Figure 26-26). When used, the currently selected widget will increase in size horizontally or vertically to fill the available space around it.

Figure 26-26

Design Time Tools Positioning

The chapter entitled “A Guide to the Android Studio Layout Editor Tool” introduced the concept of the tools namespace and explained how it can be used to set visibility attributes that only take effect within the layout editor. Behind the scenes, Android Studio also uses tools attributes to hold widgets in position when placed on the layout without constraints. Imagine, for example, a Button placed onto the layout while autoconnect mode is disabled. While the widget will appear to be in the correct position within the preview canvas, when the app is run, it will appear in the top left-hand corner of the screen. This is because the widget has no constraints to tell the ConstraintLayout parent where to position it.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

The widget appears to be in the correct location in the layout editor because Android Studio has set absolute X and Y positioning tools attributes to keep it in the correct location until constraints can be added. Within the XML layout file, this might read as follows:

<Button
    android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    tools:layout_editor_absoluteX="111dp"
    tools:layout_editor_absoluteY="88dp" />Code language: HTML, XML (xml)

Once adequate constraints have been added to the widget, the layout editor will remove these tools attributes. A useful technique to quickly identify which widgets lack constraints without waiting until the app runs is to click on the button highlighted in Figure 26-27 to toggle tools position visibility. Any widgets that jump to the top left-hand corner are not fully constrained and are being held in place by temporary tools absolute X and Y positioning attributes.

Figure 26-27

Adding Guidelines

Guidelines provide additional elements to which constraints may be anchored. Guidelines are added by right-clicking on the layout and selecting either the Vertical Guideline or Horizontal Guideline menu option or using the toolbar menu options as shown in Figure 26-28:

Figure 26-28

Alternatively, horizontal and vertical Guidelines may be dragged from the Helpers section of the Palette and dropped either onto the layout canvas or Component Tree panel as indicated by the arrows in Figure 26-29:

Figure 26-29

Once added, a guideline will appear as a dashed line in the layout and may be moved by clicking and dragging the line. To establish a constraint connection to a guideline, click on the constraint handler of a widget and drag it to the guideline before releasing. In Figure 26-30, the left sides of two Buttons are connected by constraints to a vertical guideline.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

The position of a vertical guideline can be specified as an absolute distance from either the left or the right of the parent layout (or the top or bottom for a horizontal guideline). For example, the vertical guideline in the figure below is positioned at 97dp from the left-hand edge of the parent:

Figure 26-30

Alternatively, the guideline may be positioned as a percentage of the overall width or height of the parent layout. To switch between these three modes, select the guideline and click on the circle at the bottom or end of the guideline (depending on whether the guideline is vertical or horizontal). Figure 26-31, for example, shows a guideline positioned based on percentage:

Figure 26-31

Adding Barriers

Barriers are added by right-clicking on the layout and selecting either the Vertical or Horizontal Barrier option from the Add helpers menu or using the toolbar menu options, as shown in Figure 26-28. Alternatively, locate the Barrier types in the Helpers section of the Palette and drag and drop them either onto the layout canvas or the Component Tree panel.

Once a barrier has been added to the layout, it will appear as an entry in the Component Tree panel:

Figure 26-32

To add views as reference views (in other words, the views that control the position of the barrier), drag the widgets from within the Component Tree onto the barrier entry. In Figure 26-33, for example, widgets named textView2 and textView3 have been assigned as the reference widgets for the barrier:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 26-33

After the reference views have been added, the barrier needs to be configured to specify the direction of the barrier relative to those views. This is the barrier direction setting and is defined within the Attributes tool window when the barrier is selected in the Component Tree panel:

Figure 26-34

The following figure shows a layout containing a barrier declared with textView1 and textView2 acting as the reference views and textview3 as the constrained view. Since the barrier is pushing from the end of the reference views towards the constrained view, the barrier direction has been set to end:

Figure 26-35

Adding a Group

To add a Group to a layout, right-click on the layout and select the Group option from the Add helpers menu or use the toolbar menu options shown in Figure 26-28. Alternatively, locate the Group item in the Helpers section of the Palette and drag and drop it either onto the layout canvas or Component Tree panel.

To add widgets to the group, select them in the Component Tree and drag and drop them onto the Group entry. Figure 26-36, for example, shows three selected widgets being added to a group:

Figure 26-36

Any widgets referenced by the group will appear italicized beneath the group entry in the Component Tree, as shown in Figure 26-37. To remove a widget from the group, select it and tap the keyboard delete key:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 26-37

Once widgets have been assigned to the group, use the Constraints section of the Attributes tool window to modify the visibility setting:

Figure 26-38

Working with the Flow Helper

Flow helpers may be added using either the menu or Palette, as outlined previously for the other helpers. As with the Group helper (Figure 26-36), widgets are added to a Flow instance by dragging them within the Component Tree onto the Flow entry. Having added a Flow helper and assigned widgets to it, select it in the Component Tree and use the Common Attributes section of the Attribute tool window to configure the flow layout behavior:

Figure 26-39

Widget Group Alignment and Distribution

The Android Studio Layout Editor tool provides a range of alignment and distribution actions that can be performed when two or more widgets are selected in the layout. Shift-click on each of the widgets to be included in the action, right-click on the layout and make a selection from the many options displayed in the Align menu:

Figure 26-40

As shown in Figure 26-41 below, these options are also accessible via the Align button located in the Layout Editor toolbar:

Figure 26-41

Similarly, the Pack menu (Figure 26-42) can be used to collectively reposition the selected widgets so that they are packed tightly together, either vertically or horizontally. It achieves this by changing the widgets’ absolute x and y coordinates but does not apply any constraints. The two distribution options in the Pack menu, on the other hand, move the selected widgets so that they are spaced evenly apart in either vertical or horizontal axis and apply constraints between the views to maintain this spacing:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Iguana Kotlin Edition of this publication in eBook or Print format.

The full book contains 99 chapters and over 842 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 26-42

Converting other Layouts to ConstraintLayout

For existing user interface layouts that use one or more of the other Android layout classes (such as RelativeLayout or LinearLayout), the Layout Editor tool provides an option to convert the user interface to use the ConstraintLayout.

The Component Tree panel is displayed beneath the Palette when the Layout Editor tool is open and in Design mode. To convert a layout to ConstraintLayout, locate it within the Component Tree, right-click on it, and select the Convert <current layout> to Constraint Layout menu option:

Figure 26-43

When this menu option is selected, Android Studio will convert the selected layout to a ConstraintLayout and use inference to establish constraints designed to match the layout behavior of the original layout type.

Summary

A redesigned Layout Editor tool combined with ConstraintLayout makes designing complex user interface layouts with Android Studio a relatively fast and intuitive process. This chapter has covered the concepts of constraints, margins, and bias in more detail while also exploring how ConstraintLayout-based design has been integrated into the Layout Editor tool.