24. A Guide to the Android Studio Layout Editor Tool

It is difficult to think of an Android application concept that does not require some form of user interface. Most Android devices come equipped with a touch screen and keyboard (either virtual or physical) and taps and swipes are the primary form of interaction between the user and application. Invariably these interactions take place through the application’s user interface.

A well designed and implemented user interface, an important factor in creating a successful and popular Android application, can vary from simple to extremely complex, depending on the design requirements of the individual application. Regardless of the level of complexity, the Android Studio Layout Editor tool significantly simplifies the task of designing and implementing Android user interfaces.

24.1 Basic vs. Empty Activity Templates

As outlined in the chapter entitled “The Anatomy of an Android Application”, Android applications are made up of one or more activities. An activity is a standalone module of application functionality that usually correlates directly to a single user interface screen. As such, when working with the Android Studio Layout Editor we are invariably working on the layout for an activity.

When creating a new Android Studio project, a number of different templates are available to be used as the starting point for the user interface of the main activity. The most basic of these templates are the Basic Activity and Empty Activity templates. Although these seem similar at first glance, there are actually considerable differences between the two options. To see these differences within the layout editor, use the View Options menu to enable Show System UI as shown in Figure 24-1 below:

Figure 24-1

The Empty Activity template creates a single layout file consisting of a ConstraintLayout manager instance containing a TextView object as shown in Figure 24-2:

Figure 24-2

The Basic Activity, on the other hand, consists of multiple layout files. The top level layout file has a CoordinatorLayout as the root view, a configurable app bar (also known as an action bar) that appears across the top of the device screen (marked A in Figure 24-3) and a floating action button (the email button marked B). In addition to these items, the activity_main.xml layout file contains a reference to a second file named content_main.xml containing the content layout (marked C):

Figure 24-3

The Basic Activity contains layouts for two screens, both containing a button and a text view. The purpose of this template is to demonstrate how to implement navigation between multiple screens within an app. If an unmodified app using the Basic Activity template were to be run, the first of these two screens would appear (marked A in Figure 24-4). Pressing the Next button, would navigate to the second screen (B) which, in turn, contains a button to return to the first screen:

Figure 24-4

This app behavior makes use of two Android features referred to as fragments and navigation, both of which will be covered starting with the chapters entitled “An Introduction to Android Fragments” and “An Overview of the Navigation Architecture Component” respectively.

The content_main.xml file contains a special fragment known as a Navigation Host Fragment which allows different content to be switched in and out of view depending on the settings configured in the res -> layout -> nav_graph.xml file. In the case of the Basic Activity template, the nav_graph.xml file is configured to switch between the user interface layouts defined in the fragment_first.xml and fragment_second.xml files based on the Next and Previous button selections made by the user.

Clearly the Empty Activity template is useful if you need neither a floating action button nor a menu in your activity and do not need the special app bar behavior provided by the CoordinatorLayout such as options to make the app bar and toolbar collapse from view during certain scrolling operations (a topic covered in the chapter entitled “Working with the AppBar and Collapsing Toolbar Layouts”). The Basic Activity is useful, however, in that it provides these elements by default. In fact, it is often quicker to create a new activity using the Basic Activity template and delete the elements you do not require than to use the Empty Activity template and manually implement behavior such as collapsing toolbars, a menu or floating action button.

Since not all of the examples in this book require the features of the Basic Activity template, however, most of the examples in this chapter will use the Empty Activity template unless the example requires one or other of the features provided by the Basic Activity template.

For future reference, if you need a menu but not a floating action button, use the Basic Activity and follow these steps to delete the floating action button:

1. Double-click on the main activity_main.xml layout file located in the Project tool window under app -> res -> layout to load it into the Layout Editor. With the layout loaded into the Layout Editor tool, select the floating action button and tap the keyboard Delete key to remove the object from the layout.

2. Locate and edit the Kotlin code for the activity (located under app -> java -> <package name> -> <activity class name> and remove the floating action button code from the onCreate method as follows:

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)

 

    binding = ActivityMainBinding.inflate(layoutInflater)

    setContentView(binding.root)

 

    setSupportActionBar(binding.toolbar)

 

    val navController = findNavController(R.id.nav_host_fragment_content_main)

    appBarConfiguration = AppBarConfiguration(navController.graph)

    setupActionBarWithNavController(navController, appBarConfiguration)

}

If you need a floating action button but no menu, use the Basic Activity template and follow these steps:

1. Edit the activity class file and delete the onCreateOptionsMenu and onOptionsItemSelected methods.

2. Select the res -> menu item in the Project tool window and tap the keyboard Delete key to remove the folder and corresponding menu resource files from the project.

If you need to use the Basic Activity template but need neither the navigation features nor the second content fragment, follow these steps:

1. Within the Project tool window, navigate to and double-click on the app -> res -> navigation -> nav_graph.xml file to load it into the navigation editor.

2. Within the editor, select the SecondFragment entry in the graph panel and tap the keyboard delete key to remove it from the graph.

3. Locate and delete the SecondFragment.kt (app -> java -> <package name> -> SecondFragment) and fragment_second.xml (app -> res -> layout -> fragment_second.xml) files.

4. The final task is to remove some code from the FirstFragment class so that the Button view no longer navigates to the now non-existent second fragment when clicked. Locate the FirstFragment.kt file, double click on it to load it into the editor and remove the code from the onViewCreated() method so that it reads as follows:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    super.onViewCreated(view, savedInstanceState)

}

24.2 The Android Studio Layout Editor

As has been demonstrated in previous chapters, the Layout Editor tool provides a “what you see is what you get” (WYSIWYG) environment in which views can be selected from a palette and then placed onto a canvas representing the display of an Android device. Once a view has been placed on the canvas, it can be moved, deleted and resized (subject to the constraints of the parent view). Further, a wide variety of properties relating to the selected view may be modified using the Attributes tool window.

Under the surface, the Layout Editor tool actually constructs an XML resource file containing the definition of the user interface that is being designed. As such, the Layout Editor tool operates in three distinct modes referred to as Design, Code and Split modes.

24.3 Design Mode

In design mode, the user interface can be visually manipulated by directly working with the view palette and the graphical representation of the layout. Figure 24-5 highlights the key areas of the Android Studio Layout Editor tool in design mode:

Figure 24-5

A – Palette – The palette provides access to the range of view components provided by the Android SDK. These are grouped into categories for easy navigation. Items may be added to the layout by dragging a view component from the palette and dropping it at the desired position on the layout.

B – Device Screen – The device screen provides a visual “what you see is what you get” representation of the user interface layout as it is being designed. This layout allows for direct manipulation of the design in terms of allowing views to be selected, deleted, moved and resized. The device model represented by the layout can be changed at any time using a menu located in the toolbar.

C – Component TreeAs outlined in the previous chapter (“Understanding Android Views, View Groups and Layouts”) user interfaces are constructed using a hierarchical structure. The component tree provides a visual overview of the hierarchy of the user interface design. Selecting an element from the component tree will cause the corresponding view in the layout to be selected. Similarly, selecting a view from the device screen layout will select that view in the component tree hierarchy.

D – Attributes – All of the component views listed in the palette have associated with them a set of attributes that can be used to adjust the behavior and appearance of that view. The Layout Editor’s attributes panel provides access to the attributes of the currently selected view in the layout allowing changes to be made.

E – Toolbar – The Layout Editor toolbar provides quick access to a wide range of options including, amongst other options, the ability to zoom in and out of the device screen layout, change the device model currently displayed, rotate the layout between portrait and landscape and switch to a different Android SDK API level. The toolbar also has a set of context sensitive buttons which will appear when relevant view types are selected in the device screen layout.

F – Mode Switching Controls – These three buttons provide a way to switch back and forth between the Layout Editor tool’s Design, Code and Split modes.

G - Zoom and Pan Controls - This control panel allows you to zoom in and out of the design canvas and to grab the canvas and pan around to find areas that are obscured when zoomed in.

24.4 The Palette

The Layout Editor palette is organized into two panels designed to make it easy to locate and preview view components for addition to a layout design. The category panel (marked A in Figure 24-6) lists the different categories of view components supported by the Android SDK. When a category is selected from the list, the second panel (B) updates to display a list of the components that fall into that category:

Figure 24-6

To add a component from the palette onto the layout canvas, simply select the item either from the component list or the preview panel, drag it to the desired location on the canvas and drop it into place.

A search for a specific component within the currently selected category may be initiated by clicking on the search button (marked C in Figure 24-6 above) in the palette toolbar and typing in the component name. As characters are typed, matching results will appear in real-time within the component list panel. If you are unsure of the category in which the component resides, simply select the All category either before or during the search operation.

24.5 Design Mode and Layout Views

By default, the layout editor will appear in Design mode as is the case in Figure 24-5 above. This mode provides a visual representation of the user interface. Design mode can be selected at any time by clicking on the rightmost mode switching control has shown in Figure 24-7:

Figure 24-7

When the Layout Editor tool is in Design mode, the layout can be viewed in two different ways. The view shown in Figure 24-5 above is the Design view and shows the layout and widgets as they will appear in the running app. A second mode, referred to as the Blueprint view can be shown either instead of, or concurrently with the Design view. The toolbar menu shown in Figure 24-8 provides options to display the Design, Blueprint, or both views. A fourth option, Force Refresh Layout, causes the layout to rebuild and redraw. This can be useful when the layout enters an unexpected state or is not accurately reflecting the current design settings:

Figure 24-8

Whether to display the layout view, design view or both is a matter of personal preference. A good approach is to begin with both displayed as shown in Figure 24-9:

Figure 24-9

24.6 Night Mode

To view the layout in night mode during the design work, select the menu shown in Figure 24-10 below and change the setting to Night:

Figure 24-10

24.7 Code Mode

It is important to keep in mind when using the Android Studio Layout Editor tool that all it is really doing is providing a user friendly approach to creating XML layout resource files. At any time during the design process, the underlying XML can be viewed and directly edited simply by clicking on the Code button located in the top right-hand corner of the Layout Editor tool panel as shown in Figure 24-11:

Figure 24-11

Figure 24-12 shows the Android Studio Layout Editor tool in Code mode, allowing changes to be made to the user interface declaration by making changes to the XML:

Figure 24-12

24.8 Split Mode

In Split mode, the editor shows the Design and Code views side by side allowing the user interface to be modified both visually using the design canvas and by making changes directly to the XML declarations. To enter Split mode, click on the middle button shown in Figure 24-13 below:

Figure 24-13

Any changes to the XML are automatically reflected in the design canvas and vice versa. Figure 24-14 shows the editor in Split mode:

Figure 24-14

24.9 Setting Attributes

The Attributes panel provides access to all of the available settings for the currently selected component. Figure 24-15, for example, shows the attributes for the TextView widget:

Figure 24-15

The Attributes tool window is divided into the following different sections.

id - Contains the id property which defines the name by which the currently selected object will be referenced in the source code of the app.

Declared Attributes - Contains all of the properties which have already been assigned a value.

Layout - The settings that define how the currently selected view object is positioned and sized in relation to the screen and other objects in the layout.

Transforms - Contains controls allowing the currently selected object to be rotated, scaled and offset.

Common Attributes - A list of attributes that commonly need to be changed for the class of view object currently selected.

All Attributes - A complete list of all of the attributes available for the currently selected object.

A search for a specific attribute may also be performed by selecting the search button in the toolbar of the attributes tool window and typing in the attribute name.

Some attributes contain a narrow button to the right of the value field. This indicates that the Resources dialog is available to assist in selecting a suitable property value. To display the dialog, simply click on the button. The appearance of this button changes to reflect whether or not the corresponding property value is stored in a resource file or hardcoded. If the value is stored in a resource file, the button to the right of the text property field will be filled in to indicate that the value is not hard coded as highlighted in Figure 24-16 below:

Figure 24-16

Attributes for which a finite number of valid options are available will present a drop down menu (Figure 24-17) from which a selection may be made.

Figure 24-17

A dropper icon (as shown in the backgroundTint field in Figure 24-16 above) can be clicked to display the color selection palette. Similarly, when a flag icon appears in this position it can clicked to display a list of options available for the attribute, while an image icon opens the resource manager panel allowing images and other resource types to be selected for the attribute.

24.10 Transforms

The transforms panel within the Attributes tool window (Figure 24-18) provides a set of controls and properties which control visual aspects of the currently selected object in terms of rotation, alpha (used to fade a view in and out), scale (size), and translation (offset from current position):

Figure 24-18

The panel contains a visual representation of the view which updates as properties are changed. These changes are also reflected on the view within layout canvas.

24.11 Tools Visibility Toggles

When reviewing the content of an Android Studio XML layout file in Code mode you will notice that many of the attributes that define how a view is to appear and behave begin with the android: prefix. This indicates that the attributes are set within the android namespace and will take effect when the app is run. The following excerpt from a layout file, for example, sets a variety of attributes on a Button view:

<Button

    android:id="@+id/button"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Button"

.

.

In addition to the android namespace, Android Studio also provides a tools namespace. When attributes are set within this namespace, they only take effect within the layout editor preview. While designing a layout you might, for example, find it helpful for an EditText view to display some text, but require the view to be blank when the app runs. To achieve this you would set the text property of the view using the tools namespace as follows:

<EditText

    android:id="@+id/editTextTextPersonName"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:ems="10"

    android:inputType="textPersonName"

    tools:text="Sample Text"

.

.

A tool attribute of this type is set in the Attributes tool window by entering the value into the property fields marked by the wrench icon as shown in Figure 24-19:

Figure 24-19

Tools attributes are particularly useful for changing the visibility of a view during the design process. A layout may contain a view which is programmatically displayed and hidden when the app is running depending on user actions. To simulate the hiding of the view the following tools attribute could be added to the view XML declaration:

tools:visibility="invisible"

When using the invisible setting, although the view will no longer be visible, it is still present in the layout and occupies the same space it did when it was visible. To make the layout behave as though the view no longer exists, the visibility attribute should be set to gone as follows:

tools:visibility="gone"

In both examples above, the visibility settings only apply within the layout editor and will have no effect in the running app. To control visibility in both the layout editor and running app, the same attribute would be set using the android namespace:

android:visibility="gone"

While these visibility tools attributes are useful, having to manually edit the XML layout file is a cumbersome process. To make it easier to change these settings, Android Studio provides a set of toggles within the layout editor Component Tree panel. To access these controls, click in the margin to the right of the corresponding view in the panel. Figure 24-20, for example, shows the tools visibility toggle controls for a Button view named myButton:

Figure 24-20

These toggles control the visibility of the corresponding view for both the android and tools namespaces and provide not set, visible, invisible and gone options. When conflicting attributes are set (for example an android namespace toggle is set to visible while the tools value set to invisible) the tools namespace takes precedence within the layout preview. When a toggle selection is made, Android Studio automatically adds the appropriate attribute to the XML view element in the layout file.

In addition to the visibility toggles in the Component Tree panel, the layout editor also includes the tools visibility and position toggle button shown highlighted in Figure 24-21 below:

Figure 24-21

This button toggles the current tools visibility settings. If the Button view shown above currently has the tools visibility attribute set to gone, for example, toggling this button will make it visible. This makes it easy to quickly check the layout behavior as the view is added to and removed from the layout. This toggle is also useful for checking that the views in the layout are correctly constrained, a topic which will be covered in the chapter entitled “A Guide to Using ConstraintLayout in Android Studio”.

24.12 Converting Views

Changing a view in a layout from one type to another (such as converting a TextView to an EditText) can be performed easily within the Android Studio layout editor simply by right-clicking on the view either within the screen layout or Component tree window and selecting the Convert view... menu option (Figure 24-22):

Figure 24-22

Once selected, a dialog will appear containing a list of compatible view types to which the selected object is eligible for conversion. Figure 24-23, for example shows the types to which an existing TextView view may be converted:

Figure 24-23

This technique is also useful for converting layouts from one type to another (for example converting a ConstraintLayout to a LinearLayout).

24.13 Displaying Sample Data

When designing layouts in Android Studio situations will arise where the content to be displayed within the user interface will not be available until the app is completed and running. This can sometimes make it difficult to assess from within the layout editor how the layout will appear at app runtime. To address this issue, the layout editor allows sample data to be specified that will populate views within the layout editor with sample images and data. This sample data only appears within the layout editor and is not displayed when the app runs. Sample data may be configured either by directly editing the XML for the layout, or visually using the design-time helper by right-clicking on the widget in the design area and selecting the Set Sample Data menu option. The design-time helper panel will display a range of preconfigured options for sample data to be displayed on the selected view item including combinations of text and images in a variety of configurations. Figure 24-24, for example, shows the sample data options displayed when selecting sample data to appear in a RecyclerView list:

Figure 24-24

Alternatively, custom text and images may be provided for display during the layout design process. An example of using sample data within the layout editor is included in a later chapter entitled “A Layout Editor Sample Data Tutorial”. Since sample data is implemented as a tools attribute, the visibility of the data within the preview can be controlled using the toggle button highlighted in Figure 24-21 above.

24.14 Creating a Custom Device Definition

The device menu in the Layout Editor toolbar (Figure 24-25) provides a list of preconfigured device types which, when selected, will appear as the device screen canvas. In addition to the pre-configured device types, any AVD instances that have previously been configured within the Android Studio environment will also be listed within the menu. To add additional device configurations, display the device menu, select the Add Device Definition… option and follow the steps outlined in the chapter entitled “Creating an Android Virtual Device (AVD) in Android Studio”.

Figure 24-25

24.15 Changing the Current Device

As an alternative to the device selection menu, the current device format may be changed by selecting the Custom option from the device menu, clicking on the resize handle located next to the bottom right-hand corner of the device screen (Figure 24-26) and dragging to select an alternate device display format. As the screen resizes, markers will appear indicating the various size options and orientations available for selection:

Figure 24-26

24.16 Layout Validation (Multi Preview)

The layout validation (also referred to as multi preview) option allows the user interface layout to be previewed on a range of Pixel-sized screens simultaneously. To access multi preview, click on the tab located near the top right-hand corner of the Android Studio main window as indicated in Figure 24-27:

Figure 24-27

Once loaded, the panel will appear as shown in Figure 24-28 with the layout rendered on multiple Pixel device screen configurations:

Figure 24-28

24.17 Summary

A key part of developing Android applications involves the creation of the user interface. Within the Android Studio environment, this is performed using the Layout Editor tool which operates in three modes. In Design mode, view components are selected from a palette and positioned on a layout representing an Android device screen and configured using a list of attributes. In Code mode, the underlying XML that represents the user interface layout can be directly edited. Split mode, on the other hand allows the layout to be created and modified both visually and via direct XML editing. These modes combine to provide an extensive and intuitive user interface design environment.

The layout validation panel allows user interface layouts to be quickly previewed on a range of different device screen sizes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.200.77.92