Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.1 Development Essentials – Kotlin Edition

You're reading from  Android Studio 4.1 Development Essentials – Kotlin Edition

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801815987
Pages 822 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (95) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Introduction to Kotlin 12. Kotlin Data Types,Variables and Nullability 13. Kotlin Operators and Expressions 14. Kotlin Flow Control 15. An Overview of Kotlin Functions and Lambdas 16. The Basics of Object Oriented Programming in Kotlin 17. An Introduction to Kotlin Inheritance and Subclassing 18. An Overview of Android View Binding 19. Understanding Android Application and Activity Lifecycles 20. Handling Android Activity State Changes 21. Android Activity State Changes by Example 22. Saving and Restoring the State of an Android Activity 23. Understanding Android Views, View Groups and Layouts 24. A Guide to the Android Studio Layout Editor Tool 25. A Guide to the Android ConstraintLayout 26. A Guide to using ConstraintLayout in Android Studio 27. Working with ConstraintLayout Chains and Ratios in Android Studio 28. An Android Studio Layout Editor ConstraintLayout Tutorial 29. Manual XML Layout Design in Android Studio 30. Managing Constraints using Constraint Sets 31. An Android ConstraintSet Tutorial 32. A Guide to using Apply Changes in Android Studio 33. An Overview and Example of Android Event Handling 34. Android Touch and Multi-touch Event Handling 35. Detecting Common Gestures using the Android Gesture Detector Class 36. Implementing Custom Gesture and Pinch Recognition on Android 37. An Introduction to Android Fragments 38. Using Fragments in Android Studio - An Example 39. Modern Android App Architecture with Jetpack 40. An Android Jetpack ViewModel Tutorial 41. An Android Jetpack LiveData Tutorial 42. An Overview of Android Jetpack Data Binding 43. An Android Jetpack Data Binding Tutorial 44. An Android ViewModel Saved State Tutorial 45. Working with Android Lifecycle-Aware Components 46. An Android Jetpack Lifecycle Awareness Tutorial 47. An Overview of the Navigation Architecture Component 48. An Android Jetpack Navigation Component Tutorial 49. An Introduction to MotionLayout 50. An Android MotionLayout Editor Tutorial 51. A MotionLayout KeyCycle Tutorial 52. Working with the Floating Action Button and Snackbar 53. Creating a Tabbed Interface using the TabLayout Component 54. Working with the RecyclerView and CardView Widgets 55. An Android RecyclerView and CardView Tutorial 56. A Layout Editor Sample Data Tutorial 57. Working with the AppBar and Collapsing Toolbar Layouts 58. An Android Studio Master/Detail Flow Tutorial 59. An Overview of Android Intents 60. Android Explicit Intents – A Worked Example 61. Android Implicit Intents – A Worked Example 62. Android Broadcast Intents and Broadcast Receivers 63. A Basic Overview of Threads and AsyncTasks 64. An Introduction to Kotlin Coroutines 65. An Android Kotlin Coroutines Tutorial 66. An Overview of Android Started and Bound Services 67. Implementing an Android Started Service – A Worked Example 68. Android Local Bound Services – A Worked Example 69. Android Remote Bound Services – A Worked Example 70. An Android Notifications Tutorial 71. An Android Direct Reply Notification Tutorial 72. Foldable Devices and Multi-Window Support 73. An Overview of Android SQLite Databases 74. The Android Room Persistence Library 75. An Android TableLayout and TableRow Tutorial 76. An Android Room Database and Repository Tutorial 77. Accessing Cloud Storage using the Android Storage Access Framework 78. An Android Storage Access Framework Example 79. Video Playback on Android using the VideoView and MediaController Classes 80. Android Picture-in-Picture Mode 81. An Android Picture-in-Picture Tutorial 82. Making Runtime Permission Requests in Android 83. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 84. Printing with the Android Printing Framework 85. An Android HTML and Web Content Printing Example 86. A Guide to Android Custom Document Printing 87. An Introduction to Android App Links 88. An Android Studio App Links Tutorial 89. A Guide to the Android Studio Profiler 90. An Android Biometric Authentication Tutorial 91. Creating, Testing and Uploading an Android App Bundle 92. An Overview of Android Dynamic Feature Modules 93. An Android Studio Dynamic Feature Tutorial 94. An Overview of Gradle in Android Studio Index

26. A Guide to 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 the ways in which the Layout Editor tool allows ConstraintLayout-based user interfaces to be designed and implemented.

26.1 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. The Layout view, on the other hand, displays a blueprint style of view where the widgets are represented by shaded outlines. As can be seen in Figure 26-1 above, 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...

26.2 Autoconnect Mode

Autoconnect, as the name suggests, automatically establishes constraint connections as items are added to the layout. Autoconnect mode may be enabled and disabled 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 position of the widget and the widget’s proximity to both the sides of the parent layout and other elements in the layout. In the event that any of the automatic constraint connections fail to provide the desired behavior, these may be changed manually as outlined later in this chapter.

26.3 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 simply by dragging and dropping objects from the palette onto the layout canvas and making size and positioning changes until the layout appears as required. In essence this involves “painting” the layout without worrying about constraints. Inference mode may also be used at any time 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:

Figure 26-5

As with Autoconnect mode, there is always the possibility that the Layout Editor tool will infer...

26.4 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

Clearly 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 resize 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, simply drag...

26.5 Adding Constraints in the Inspector

Constraints may also be added to a view within the Android Studio Layout Editor tool using the Inspector panel located 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 a 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 bottom edge of the view in the above figure). To add a constraint, simply click on this blue circle and the layout editor will add a constraint connected to what it considers to be the most appropriate target within the layout.

26.6 Viewing Constraints in the Attributes Window

A list of constraints configured on the currently select widget can be viewing 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.

26.7 Deleting Constraints

To delete an individual constraint, simply 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 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

26.8 Adjusting Constraint Bias

In the previous chapter, the concept of using bias settings to favor one opposing constraint over another was outlined. 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 vertical and horizontal opposing constraints of the currently selected widget.

Figure 26-15

26.9 Understanding ConstraintLayout Margins

Constraints can be used in conjunction 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 orientation. The horizontal bias setting is also able to control the position of the widget 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...

26.10 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 essentially fix the widget at that position. The result of this 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...

26.11 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

In the above figure, both the horizontal and vertical dimensions are set 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-4

To change the current setting, simply click on the...

26.12 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 which only take effect within the layout editor. Behind the scenes, Android Studio also uses tools attributes to hold widgets in position when they are 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.

The reason that the widget appears to be in the correct location in the layout editor is because Android Studio has set absolute X and Y positioning tools attributes to keep it in the correct location until constraints...

26.13 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 Add Vertical Guideline or Add Horizontal Guideline menu option or using the toolbar menu options as shown in Figure 26-29:

Figure 26-29

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:

Figure 26-30

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

The position of a vertical guideline can be specified as an absolute distance from either the left or the...

26.14 Adding Barriers

Barriers are added by right-clicking on the layout and selecting either the Add Vertical Barrier or Add Horizontal Barrier option from the Helpers menu, or using the toolbar menu options as shown previously in Figure 26-29. Alternatively, locate the Barrier types in the Helpers section of the Palette and drag and drop them either onto the layout canvas or 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-33

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

Figure 26-34

After the reference views have been added, the barrier needs to be configured to specify the direction of the barrier in relation those views...

26.15 Adding a Group

To add a Group to a layout, right-click on the layout and select the Add Group option from the Helpers menu, or use the toolbar menu options as shown previously in Figure 26-29. 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-37 for example, shows three selected widgets being added to a group:

Figure 26-37

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

Figure 26-38

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

Figure 26-39

26.16 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-37), 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-40

26.17 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. Simply 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-41

As shown in Figure 26-42 below, these options are also available as buttons in the Layout Editor toolbar:

Figure 26-42

Similarly, the Pack menu (Figure 26-43) 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 absolute x and y coordinates of the widgets 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...

26.18 Converting other Layouts to ConstraintLayout

For existing user interface layouts that make use of 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.

When the Layout Editor tool is open and in Design mode, the Component Tree panel is displayed beneath the Palette. 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-44

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.

26.19 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 the ways in which ConstraintLayout-based design has been integrated into the Layout Editor tool.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Kotlin Edition
Published in: May 2021 Publisher: Packt ISBN-13: 9781801815987
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime}