Tuesday 18 November 2014

Android SDK: User Interface Design

In this series we're learning about Android SDK development from scratch! In this tutorial, we will build a simple user interface layout with a few visual elements.
Introduction

We will add the layout to the first app project we created and explored over the past few tutorials and we will continue working on the project throughout this series. We will primarily work with XML and the Eclipse ADT interface in this part, but will start to use a little Java in the next two parts. Both XML and Java coding are involved in many aspects of Android development, so you will need to get a grasp of the basics in these languages if you have not already. If you are new to either language, you will use what we learn in this series as a foundation for future learning.

1. XML Basics

Before we start on layouts, let's run through some XML basics for those who haven't used the markup language before. If you are already familiar with XML, skip to part two of this tutorial. XML is a language that stores data values. XML files are used for many different purposes. They function like databases in some projects and often model Web page output. If you've used HTML before you should be familiar with the essential features.

In XML, data values are stored in elements. A single element typically includes an opening tag and a closing tag as in this example:

1
<product>Onion</product>
As you can see, the opening tag and closing tag are the same except for the leading slash "/" indicating the closing tag. The data value in this case is the element content, the text string "Onion". The opening tag can also contain attributes for additional information about the data item:

1
<product type="vegetable">Onion</product>
Each attribute has a name and a value, with the value enclosed in quotes. Elements can also contain other elements:

<section name="food">
<product type="vegetable">Onion</product>
<product type="fruit">Banana</product>
</section>
In such a structure we say that the section element is parent and the products are child elements. The two child elements are also referred to as siblings. In an XML document, there must be one root element which acts as parent to all elements contained, or "nested", within it. This creates a tree structure, with child elements branching out from parent elements. A child element can also be a parent element if it also contains further child elements.

One other XML structure you will see is the self-closing element, which does not have separate opening and closing tags:

1
<order number="12345" customerID="a4d45s"/>
The slash "/" character at the end of the element closes it.

All of the resource files we work with on Android use XML markup, including layout files, drawables, data values, and the Manifest.

2. Android Layouts

Step 1
When you work with XML in the Eclipse IDE with the ADT installed, the coding process is a little easier by the contextual prompts you will see as you type. Open your new app's main layout file in the editor and make sure you have the XML editing tab selected so that we can work on the code directly. This is the layout for the main screen users see when the app is launched. Eclipse entered a basic layout for us to work with:

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>
As you can see, the root element is a layout element, in this case a RelativeLayout. There are a few different layout types on Android and you can nest layouts inside one another. The root layout element here has a number of attributes indicating additional information about the layout, such as the width, height, and margins. Inside the layout element is a TextView - this lets you display a text string. The TextView is a type of View. Views are the visible and interactive elements that make up your app UI. Therefore each screen in your app is a selection of Views arranged using one or more layouts. In Android, the layouts are described as ViewGroup objects, with each ViewGroup containing one or more Views.

Step 2
To focus on the basic building blocks of a layout, delete the existing content of your main layout file and we will start from scratch. As we mentioned earlier in the series, you can build your layouts and Views in Java code, but the Android tools lend themselves to use XML for designing your app UIs, since you can see the visible results while you build the elements. There may be cases when it makes sense to build some or all of a UI in Java, but for the most part you should use XML. This practice also keeps the application logic and presentation elements separate.

The first task to build a layout is to choose a layout type. Let's start with one of the simplest: a LinearLayout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- views go here -->

</LinearLayout>

The LinearLayout arranges the Views we want to display along either a horizontal or vertical line. In this case the orientation is vertical so each View is added to the screen below the last. A horizontal layout adds Views left to right. The layout fills the available space both horizontally and vertically using the "layout_width" and "layout_height" attributes (on Android these are often referred to as layout parameters).

Add a new line after the line in which the "layout_height" is declared. Start typing an attribute by entering "android:". When you type the colon, Eclipse should prompt you with a list of relevant attributes. You can either continue typing to narrow the suggestion list or scroll through it to select one with your mouse. Select the "android:gravity" attribute.

Enter "center_horizontal" as the gravity value so that the contained elements is displayed centered on the X axis:

1
android:gravity="center_horizontal"
This applies to everything inside the layout. We can set several additional display properties such as padding, margins, and backgrounds. But let's keep things simple for now.

3. Adding Views

Step 1
Next, we'll add some Views to the layout. The Views are the visible elements in the UI. Let's add some text and a button. Inside the LinearLayout element (between the opening and closing tags), start by typing "<" and Eclipse should prompt you with a list of available elements as it did with the attribute.

Select TextView from the list. Notice that this is a self-closing element, most of the Views are. Give the TextView attributes, starting with the layout width and height (type "android:" and use the prompts):

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
We set the View wide enough to accommodate its content using "wrap_content", rather than filling the parent as we did with the layout. Add another attribute to the TextView, this time listing the text string to display within it:

android:text="Hello there"
When you save the file you will see that Eclipse displays a warning message. If you hover over it, the editor margin displays the text, which also is displayed in the Problems view. It reads "Hardcoded string ... should use @string resource". The recommended practice is to store each text string value as a values resource, rather than including it directly in the layout XML. Although this may seem extra work for no reason at first, it is worth getting into the habit of doing so, as you will see the benefit of it when your projects get bigger. Find the "res/values/strings.xml" file in your Package Explorer and open it. Switch to the "strings.xml" tab to edit the code.

You will see that Eclipse has added a few strings already. Add another, giving it a name and value:

1
<string name="hello">Hello there</string>
This means that if you use the same string in more than one place in the app UI, and if you later decide to change it, you only have to do so in one place. Save the strings file and switch back to the layout file. Alter your TextView "text" attribute to refer to the string in the values file:

1
android:text="@string/hello"
We use the string name preceded by "@string" to tell the Android tools where to find the string resource. The warning should disappear. Eclipse does this often while you are coding, to indicate errors and warnings. You can choose whether or not to observe warnings, but for errors you need to take action or your app will not function.

Step 2
After the TextView, add a Button:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/click" />
The Button uses the same attributes as the TextView in this case. But many more attributes are possible, and in general different views require different attributes. The "text" attribute value appears on the button. Add the string to your "res/values/strings.xml" file as before:

1
<string name="click">Click Me!</string>
In the next tutorial we will handle clicks on the button. Switch back to your layout file. Look at the Outline view to the right of the editor, it displays another interface to the file elements. Double-clicking the listed items jumps to their location in code. You can also expand and collapse parent elements. This is particularly useful when your layouts become more complex.

Tip: To tidy up any file that's opened in the Eclipse editor, select all using "Ctrl+A" then click "Ctrl+I" to apply indentation.
4. Graphical Layout

Step 1
Make sure your layout file is saved and switch to the Graphical Layout tab.

You can see a visual representation of your layout as you design it. The Palette area to the left allows you to select UI items and drag them onto the layout. However, to begin with, you should use XML at least until you have a grasp of the basics. XML gives you control over the details, so even if you do use the graphical tools, you will likely need to edit the XML results.

At the top of the Graphical Layout view there is a drop-down list from which you can select devices to see your layout on, as well as tools to switch orientation and zoom. Experiment with the Graphical Layout controls as you design your layouts. There are several other layout elements and settings to explore as well.

Step 2
Initially you might notice that in the layout visible elements appear very close to the top edge of the screen. Let's sort this out. Switch back to the XML editing tab and add a margin attribute to the LinearLayout:

1
android:layout_margin="10dp"
We use "dp" for density-independent pixels so that the design scales to the density of the user screen automatically. Save the file and switch back to the Graphical Layout to see the effect.

The Graphical Layout is a useful reference tool while you design your layouts, but it is only a guide. To see how your layouts appear and function while your apps run, you have to load them onto either virtual or physical devices. We will look at this later on in this series.

5. Options

You can include a variety of layout types and Views to your app screens, but the basic process remains the same. We used a LinearLayout above, but there are many others. Among the most common are the RelativeLayout, FrameLayout, AbsoluteLayout, and GridLayout. You will find all these types in the Graphical Layout Palette so feel free to try some of them out and add a few Views of your choice to them. When you add elements from the Graphical Layout tool, switch to XML each time to see what markup code this produces.

The Android platform provides Views for many common purposes, like radio buttons, checkboxes, and text input fields. These save on the amount of functionality you implement manually, but if you need a UI element that is not provided, you can create a custom View class of your own. In general it's best to do this only if you have no other option, as the standard UI elements are more reliable on user devices. They also save development and testing time.

Conclusion

In this tutorial we covered the basics necessary to design user interface layouts on Android, but we only scratched the surface of what's possible. In the next part of this series, we will add some user interaction to the app, and detect and respond to clicks on the button we added. After that, we will look at the most relevant Java concepts we need to understand about Android before delving further into the various ingredients and practices involved in app development.

No comments:

Post a Comment