Designing a User Interface using the Android Studio Designer Tool

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
A Guide to the Android Studio Designer ToolCreating an Android User Interface in Java Code using Android Studio


You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio 2.3 / Android 7 Edition of this publication in eBook ($19.99) or Print ($45.99) format

Android Studio 2.3 Development Essentials - Android 7 Edition Print and eBook (ePub/PDF/Kindle) editions contain 77 chapters and over 810 pages

Buy eBook Buy Print Preview Book


By far the easiest and most productive mechanism for designing a user interface for an Android application is to make use of the Android Studio Designer tool. The goal of this chapter is to provide an overview of how to create a user interface using this tool. The exercise included in this chapter will also be used as an opportunity to outline the creation of an activity starting with a “bare-bones” Android Studio project.

Having covered the use of the Android Studio Designer, the chapter will also provide an overview of the concepts behind manually writing and editing XML layout resource files before introducing the Hierarchy Viewer tool.




An Android Studio Designer Tool Example

The first step in this phase of the example is to create a new Android Studio project. Begin, therefore, by launching Android Studio and closing any previously opened projects by selecting the File -> Close Project menu option. Within the Android Studio welcome screen click on the Start a new Android Studio project quick start option to display the first screen of the new project dialog.

Enter LayoutSample into the Application name field and ebookfrenzy.com as the Company Domain setting before clicking on the Next button.

In previous examples, we have requested that Android Studio create a template activity for the project. We will, however, be using this tutorial to learn how to create an entirely new activity and corresponding layout resource file manually, so make sure that the Add No Activity option is selected before clicking on Finish to create the new project.


Creating a New Activity

Once the project creation process is complete, the Android Studio main window should appear with a blank background containing a message that reads “No files are open”.

The next step in the project is to create a new activity. This will be a valuable learning exercise since there are many instances in the course of developing Android applications where new activities need to be created from the ground up.

Begin by displaying the Project tool window using the Alt-1 keyboard shortcut. Once displayed, unfold the hierarchy by clicking on the right facing arrows next to the entries in the Project window. The objective here is to gain access to the app -> java -> com.ebookfrenzy.layoutsample folder in the project hierarchy. Once the package name is visible, right click on it and select the New -> Activity -> Blank Activity menu option as illustrated in Figure 16-1:


Adding a new Activity to an Android Studio project

Figure 16-1


In the resulting New Activity dialog, name the new activity LayoutSampleActivity, the layout activity_layout_sample and the menu resource menu_layout_sample.

In order for an application to be able to run on a device it needs to have an activity designated as the launcher activity. Without a launcher activity, the operating system will not know which activity to start up when the application first launches and, as such, the application will fail to start. Since this example only has one activity, it needs to be designated as the launcher activity for the application so make sure that the Launcher Activity option is selected before clicking on the Finish button.

At this point Android Studio should have added two files to the project. The Java source code file for the activity should be located in the app -> java -> com.ebookfrenzy.layoutsample folder.

In addition, the XML layout file for the user interface should have been created in the app -> res -> layout folder and should also have been preloaded into the Designer tool.

Finally, the new activity should have been added to the AndroidManifest.xml file and designated as the launcher activity. The manifest file can be found in the project window under the app -> manifests folder and should contain the following XML:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ebookfrenzy.layoutsample" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".LayoutSampleActivity"
            android:label="@string/title_activity_layout_sample" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category 
                   android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Designing the User Interface

Locate and double click on the activity_layout_sample.xml layout file located in the app -> res -> layout folder to load it into the Designer tool.

By default the layout should contain a single component view in the form of the TextView displaying the “Hello World!” message. Select this component and remove it by pressing the keyboard delete key.

From within the Widgets palette category, drag a Button view object into the center of the display view. Note that green horizontal and vertical dashed lines appear to indicate the center axes of the display. Once centered, release the mouse button to drop the view into position. Click and drag a Plain Text object from the Text Fields section of the palette and position it so that it appears above the button as illustrated in Figure 16-2:

An example Android Studio Designer user interface layout

Figure 16-2


Click on the light bulb icon to display the hints menu and click on the message that reads “This text field does not specify an inputType or a hint” and select text as the input type in the Set Attribute dialog. Click on OK to dismiss the dialog and set the attribute.

Editing View Properties

Once a view object has been placed into the user interface, the properties of that view may also be modified from within the Designer tool. In the first instance, the width of the EditText object may be inadequate for allowing the user to enter text. In order to change this, select the EditText object and locate and select the Width property in the Properties panel. In the value field, enter a value for the desired width of the field. The value must include a unit of measurement from the following list:

  • in – Inches
  • mm – Millimeters
  • pt – Points (1/72 of an inch)
  • dp – Density-independent pixels. An abstract unit of measurement based on the physical density of the device display relative to a 160dpi display baseline.
  • sp – Scale-independent pixels. Similar to dp but scaled based on the user’s font preference.
  • px – Actual screen pixels. Use is not recommended since different displays will have different pixels per inch. Use dp in preference to this unit.

For the purposes of this example, we will use density independent pixels as our unit of measurement, so enter 350dp into the dialog and click on the OK button. The width of the EditText view should change accordingly.

Next, double click on the Button view and in the resulting panel, change the text property from “New Button” to “Press Me”. Click on the light bulb icon followed by the I18N message to display the Extract Resource dialog. Name the resource button_string and click on OK to create a string resource for the button.

The very simple user interface design is now complete. Designing a more complex user interface layout is a continuation of the steps outlined above. Simply drag and drop views onto the display, position and set properties as needed and nest layouts as required.

Running the Application

All that remains is to test that the application runs. Click on the run button in the main window toolbar. Select either the simulator or a physical Android device and wait for the application to start. Assuming the absence of errors, the application and activity should launch and appear exactly as designed using the Designer tool.

Manually Creating an XML Layout

Whilst the design of layouts using the layout tool greatly improves productivity, it is still possible to create XML layouts by manually editing the XML. The structure of an XML layout file is actually quite straightforward and follows the hierarchical approach of the view tree. The first line of an XML resource file should ideally include the following standard declaration:

<?xml version="1.0" encoding="utf-8"?>

This declaration should be followed by the root element of the layout, typically a container view such as a layout manager. This is represented by both opening and closing tags and any properties that need to be set on the view. The following XML, for example, declares a RelativeLayout view as the root element and sets match_parent properties such that it fills all the available space of the device display with padding on each side of 64 density independent pixels:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="64dp"
    android:paddingBottom="64dp"
    tools:context=
     "com.ebookfrenzy.layoutsample.layoutsample.LayoutSampleActivity">

</RelativeLayout>

You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio 2.3 / Android 7 Edition of this publication in eBook ($19.99) or Print ($45.99) format

Android Studio 2.3 Development Essentials - Android 7 Edition Print and eBook (ePub/PDF/Kindle) editions contain 77 chapters and over 810 pages

Buy eBook Buy Print Preview Book

Any children that need to be added to the RelativeLayout parent must be nested within the opening and closing tags. In the following example, a Button and an EditText field have been added as children of the RelativeLayout view:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="64dp"
    android:paddingBottom="64dp"
    tools:context=
     "com.ebookfrenzy.layoutsample.layoutsample.LayoutSampleActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_string"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_above="@+id/button"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="51dp"
        android:inputType="text"
        android:width="350dp" />

</RelativeLayout>

Also, note that the two child views have a number of properties declared. In the case of the Button view, it has been assigned ID “button” and configured to display the text that is represented by a string resource named button_string. Additionally, it has been centered vertically and horizontally within the parent view and wrap_content height and width properties have been declared so that the button is sized to accommodate the content (in this case the text shown on the button).

The EditText view, on the other hand, has a width declared as 350dp, is centered horizontally within the parent and positioned 51dp above the button view.

This XML file is, of course, the layout that was created using the Designer tool in this chapter. When to write XML manually as opposed to using the Designer tool in design mode is a matter of personal preference. There are, however, advantages to using design mode. Firstly, design mode will generally be quicker given that it avoids the necessity to type lines of XML. Additionally, design mode avoids the necessity to learn the intricacies of the various property values of the Android SDK view classes. Rather than continually refer to the Android documentation to find the correct keywords and values, most properties can be located by referring to the Properties panel.

All the advantages of design mode aside, it is important to keep in mind that the two approaches to user interface design are in no way mutually exclusive. As an application developer, it is quite likely that you will end up creating user interfaces within design mode whilst performing fine-tuning and layout tweaks of the design by directly editing the generated XML resources. Both views of the interface design are, after all, a single mouse click apart within the Android Studio environment making it easy to switch back and forth as needed. In fact, a useful tip to remember is that selecting a view in the display layout and pressing the Ctrl-B keyboard shortcut will automatically jump to and highlight the XML for that view in the resource file.

Using the Hierarchy Viewer

A useful tool for closely inspecting the view hierarchy of an activity is the Hierarchy Viewer. The main purpose of the tool is to provide a detailed overview of the entire view tree for activities within currently running applications and to provide some insight into the layout rendering performance.

The hierarchy viewer can only be used to inspect applications that are either running within an Android emulator, or on a device running a development version of Android. To run the tool on the LayoutSample application created in this chapter, launch the application on an Android Virtual Device emulator and wait until it has loaded and is visible on the emulator display. Once running, select the Tools -> Android -> Android Device Monitor menu option. In the DDMS window, select the Window -> Open Perspective… menu option and choose Hierarchy View from the resulting dialog before clicking on the OK button.

When the Hierarchy Viewer appears, it will consist of a number of different panels. The left hand panel, illustrated in Figure 16 315 3, lists all the windows currently active on the device or emulator such as the navigation bar, status bar and launcher. The window listed in bold is the current foreground window, which should, in this case, be LayoutSampleActivity.


The list of processes in the Android Studio DDMS tool

Figure 16-3


Selecting the layout sample window will cause the hierarchy to load into the Tree View panel as shown in Figure 16-4 (note that there may be a short delay between selection of the window and the hierarchy diagram appearing):


The Android Studio Hierarchy Viewer Tree View panel

Figure 16-4


Whilst it is possible to zoom in and out of the tree view using the scale at the bottom of the panel or by spinning the mouse wheel, in most cases the tree will be too large to view entirely within the Tree View panel. To move the view window around the tree simply click and drag in the Tree View panel, or move the lens within the Tree Overview panel (Figure 16-5):


The Android Studio Hierarchy Viewer Tree Overview panel

Figure 16-5


When reviewing the tree view, keep in mind that some views in addition to those included in the activity layout will be displayed. These are the views and layouts that, for example, display the action bar across the top of the screen and provide an area for the activity to be displayed.

Selecting a node in the Tree View will cause the corresponding element in the user interface representation to be highlighted in red in the Layout View. In Figure 16-6 the RelativeLayout view is currently selected:


The layout representation in the Android Studio Hierarchy Viewer tool

Figure 16-6


Similarly, selecting views from the Layout View will cause the corresponding node in the Tree View to highlight and move into view.

Additional information about a view can be obtained by selecting the node within the Tree View. A panel will then popup next to the node and can be dismissed by performing a right-click on the node. Double clicking on a node will display a dialog containing a rendering of how the view appears within the application user interface. Figure 16-7, for example, shows the button from the LayoutSample application:


Inspecting a view component in the Android Studio Hierarchy Viewer

Figure 16-7


Options are also available within the tool to perform tasks such as invalidating a selected layout view (thereby forcing it to be redrawn) and to save the tree view as a PNG image file.The hierarchy viewer can also be used to display information about the speed with which the child views of a selected node are rendered when the user interface is created. To display this performance information, select the node to act as the root view and click on the toolbar button indicated in Figure 16-8. When enabled, the colored dots within the nodes indicate the performance in each category (measure, layout and draw) with red indicating slower performance for the view relative to other views in the activity. Container views with larger numbers of child views may display red status simply because the view has to wait for each child to render. This is not necessarily an indication of a performance problem with that view.


Obtaining performance information in the Android Studio Hierarchy Viewer

Figure 16-8

Summary

The Android Studio Designer tool provides a visually intuitive method for designing user interfaces. Using a drag and drop paradigm combined with a set of property editors, the tool provides considerable productivity benefits to the application developer.

User interface designs may also be implemented by manually writing the XML layout resource files, the format of which is well structured and easily understood.

The fact that the Designer tool generates XML resource files means that these two approaches to interface design can be combined to provide a “best of both worlds” approach to user interface development.

Finally, a detailed overview of the view tree for an activity and an indication of the performance of each view within that activity can be obtained using the Hierarchy Viewer tool.


You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio 2.3 / Android 7 Edition of this publication in eBook ($19.99) or Print ($45.99) format

Android Studio 2.3 Development Essentials - Android 7 Edition Print and eBook (ePub/PDF/Kindle) editions contain 77 chapters and over 810 pages

Buy eBook Buy Print Preview Book



PreviousTable of ContentsNext
A Guide to the Android Studio Designer ToolCreating an Android User Interface in Java Code using Android Studio