Coding the Interface
As mentioned earlier, the interface for any Android app is created through the use of a layout file. A layout file is an XML file that contains the XML used to create the objects and controls that the user can interact with. The first step in coding the HelloWorld app is to modify the layout so that it has some controls that the user can interact with. Your modifications will be simple. You will make the app take a name entered by the user and display Hello [entered name] after a button click.
Double-click the activity_hello_world.xml file in the layout folder of the Package Explorer to begin work coding the interface. If it is already open in the editor, click the activity_hello_world.xml tab at the top of the editor (Figure 3.6, #1). If the Graphical Layout is displayed, click the activity_hello_world.xml tab at the bottom of the editor (Figure 3.6, #2). The XML code that creates the user interface is displayed with two elements in it. The root element is a RelativeLayout. Because Android devices have so many screen sizes and resolutions, it is often best to design the UI components as relative to one another rather than designing them as a fixed position. Because the RelativeLayout is the root, it encompasses the whole screen. You must have only one layout root in an Android layout file. All other items are children of this root element.
Figure 3.6 Editor and layout tabs.
Examine the attributes of the RelativeLayout element (Listing 3.2). A closer look at the attributes reveals a certain structure. Attributes have the format library:attribute name = "attribute value". First, all the attributes in the listing start with android: This indicates that the attribute is associated with Android SDK library and that is where the compiler should look for information on what to do. Other libraries are available from third parties. Adding other libraries will be covered later in this text. The attribute name and values differ based on the element to which they are applied.
Listing 3.2 Layout XML
- The first attributes of interest in the RelativeLayout are android:layout_width="match_parent" and android:layout_height="match_parent". These attributes define the size of the element. In this case the value "match_parent" indicates that the layout should be the height and width of the device screen. If a child element of RelativeLayout has this value for either layout_height or layout_width, it will fill up as much of the RelativeLayout as it can.
The next few attributes: paddingRight, paddingLeft, paddingBottom, and paddingTop, all tell Android that it should not fill the entire screen with the RelativeLayout. Instead, there should be blank space between the edge of the screen and the edge of the layout. The amount of space is dictated by the value. The values in these attributes are your first introduction to the use of the XML files in the values folder. To refer to values from these XML files, Android also has a specific structure. That structure is "@xml_file_name/value_name". All values are enclosed in quotation marks. The value for the attribute android:paddingBottom is "@dimen/activity_vertical_margin". This tells Android it should use the value named activity_vertical_margin from the dimens.xml file. Double-click the dimens.xml file in the values folder in the Package Explorer. The file will open to the Resources tab. Click the dimens.xml tab at the bottom of the editor. This displays the XML used to define the dimensions. The <dimen> tag is used to define each dimension. Each dimension has a name attribute, a value, and then a closing tag that looks like this: </dimen>. The value between the beginning tag and the closing tag is the value that Android uses as the size of the padding.
Valid dimensions for Android include px (pixels), in (inches), mm (millimeters), pt (points), dp/dip (density-independent pixels), and sp (scale-independent pixels). It is generally recommended that dp be used for most dimensions and sp be used for specifying font sizes. These two units of measure are relative to screen density. They help keep your UI consistent among different devices. The reason that the sp unit is recommended for fonts is because it also scales to the user’s preference in font size.
- The only child element of the RelativeLayout, and thus the only item on the screen, is a TextView. TextView is Android’s version of a label. It is primarily used to display text. This element currently has only three attributes. The two size attributes differ from the RelativeLayout in that they have the value "wrap_content". This tells Android to size the TextView to the size of the text displayed in it. The only other attribute tells Android what text to display. In this case it gets the text from the strings.xml file in the values folder. Open the strings.xml file and examine the XML to find the “hello_world” item. Note that its value is “Hello World!”, exactly what is displayed in the running app and on the Graphical Layout view of the activity_hello_world.xml file. The TextView does not have any attributes describing its positioning, so Android puts it in the first available position, which is the very top-left position in the RelativeLayout.
Switch back to the Graphical Layout view of the activity_hello_world.xml file. At the left of the layout is a panel titled Palette. Palette contains a set of folders with different components (called widgets) that can be used to design a user interface. If it is not open, click on the Form Widgets folder in the Palette. Form Widgets contains a set of widgets for designing the user interaction with your app. Hover your mouse over each of the icons to see what type of control the widget implements. Notice that some controls have multiple versions that enable you to pick the size that you want for your interface.
A TextView that displays “Hello World” is already on the layout. This is used to display your app’s message. However, the size of the text needs to be bigger. To the right of the editor should be a panel with a tab with the label Outline (Figure 3.7). If this is not present, click Window > Show View > Outline to display it. The top of the tab should show the structure of the layout. It should have RelativeLayout as its root and textView1 indented below it. The TextView should be displaying “Hello World” after it. As widgets are added to the layout, they are displayed in the structure. This is very useful because sometimes controls are added to the layout that get lost (not visible) in the Graphical Layout. However, if they are in the layout they will be displayed in the structure.
Figure 3.7 Layout Outline and Properties panels.
Below the structure is the Properties window. If you haven’t clicked anything in the Graphical Layout, that window will be displaying <No Properties>. Click “Hello World” in the Graphical Layout. The Properties window should populate with all the attributes that can be set for a TextView widget. Locate and click the ... button next to the bold attribute Text Size. The Resource Chooser window is displayed. Two dimensions created when the project was created are listed (the padding margins). Click the New Dimension button at the bottom of the Resource Chooser. In the window that opens, enter message_text_size as the dimension name and 24sp as the value. Click OK until you have closed these two windows. The size of Hello World! should be increased. Open the dimen.xml file and switch to the XML view to see the dimension you created. Close this file and click back to the activity_hello_world.xml tab. Switch from Graphical Layout to the XML view and examine the XML changes to the TextView element. Switch back to the Graphical Layout.
Locate the Small TextView widget just below the Form Widgets folder label. Click and drag it to the layout, position it as in Figure 3.8, and drop it. Notice the green arrows pointing to the left side of the layout and to the Hello World! TextView. These arrows show what object the widget is relative to for positioning purposes. Click the XML view (Listing 3.3). A number of changes have been made to the XML.
Figure 3.8 A Small TextView positioned properly on a Graphical Layout.
Listing 3.3 Layout XML with TextView Added
- The Hello World! TextView now has an attribute android:id="@+id/textView2". To correctly relatively position the new TextView, Android needed a way to reference it so it added the ID. The +id tells Android to create the ID for the widget. IDs can be defined in the ids.xml values file. However, to use these IDs for widgets, you need to define them prior to use, and they cannot be reused. Using +id enables you to tell Android to create an ID for the widget as you need it. textView2 is not a very useful ID. It does not describe what the TextView is used for, so change the ID to textViewDisplay.
- The new TextView also has a +id. However, it is different from the first one. +ids may be reused in different layouts but cannot be reused within the same layout! Next come the widget size attributes. All items in a layout must contain these attributes.
- As the arrows on the Graphical Layout showed, this widget is positioned relative to the Hello World! TextView. The layout attributes are the XML used to do the relative positioning. alignLeft tells Android to align this widget’s left edge with the referenced widget’s left edge. alignBelow tells Android to position the widget below the referenced widget.
- The margin attributes layout_marginLeft and layout_marginTop tell Android how much space to put between the widget and the referenced widget. Change the left margin to 20dp and the top margin to 55dp. You will often have to tweak these values to get the layout to look exactly the way you want it to.
- The android:text attribute indicates what text should be displayed. This attribute is underlined with a yellow triangle on the left edge. This is a warning. Hover over or click the yellow triangle. The warning is displayed. The value "Small Text" is a hard-coded value. Android wants all values to be referenced from a value’s XML file. This is for ease of maintenance. You can change a string value used multiple times just once in the strings.xml file, and the changes will be made throughout your app. Also, by substituting a different string’s.xml file, you can adapt your app to different languages more easily. To simplify this example, leave the string hard-coded but change it to meet your needs. Delete "Small Text" and replace it with "Name:".
- The final attribute in the new TextView is textAppearance. The value for this attribute references the Android attr.xml file and is used in place of the textSize attribute. The attr.xml file is a file supplied by the Android SDK. Switch back to the Graphical Layout view. The TextView you added should now be displaying Name:.
Locate and click the Text Fields folder in the Palette. A number of widgets for entering information are displayed. The widget for entering data in Android is called an EditText. Each of the EditText widgets listed is configured for the entry of a different type of data. The different configurations dictate what soft keyboard is displayed when the widget is clicked and, in some cases, how the text is formatted as it is entered. For example, the EditText with the number 42 in it will display a keyboard with only numbers on it, whereas the EditText with Firstname Lastname in it will display an alpha character keyboard and it will capitalize each word entered. Drag the Firstname Lastname EditText to the right of the Name: TextView. As you are dragging it, pay attention to the green arrows. You want this relative to the Name: TextView, so there should be only one arrow, and it should point at the TextView. A dotted green line should go from the bottom of the TextView through the EditText. This aligns the EditText with the bottom of the TextView.
Click the Form Widgets folder and drag a Small Button below the EditText. In this case you want the green arrow pointing to the EditText and the dotted green line going through the middle of the bottom, from the top of the screen to the bottom, to center it horizontally in the RelativeLayout.
Switch to the XML view for the layout. Locate the EditText element. Change the default id to "@+id/editTextName" so that we have some understanding what data that widget is handling. Change the marginLeft attribute to "5dp". There are two new attributes. The first is android:ems. This attribute sets the displayed size of the layout to 10 ems. Ems is a size measurement equal to the number of capital Ms that would fit into the control. The second new attribute is android:inputType. This attribute tells Android how you want text handled as it’s entered and the type of keyboard to display when the user is entering data.
Locate the Button element. Change the default id to "@+id/buttonDisplay". There is also a new attribute in this element: layout_centerHorizontal. This attribute is set to true to tell Android to center the widget in the parent. Finally, change the text attribute to "Display". Change the value in the layout_below attribute to @+id/editTextName to match the change you made in the EditText element. Switch to the Graphical Layout to see the changes.
Run the app in the emulator using Run > Run Configurations > HelloWorldRunConfig and click the Run button to see the layout as it would appear running (Figure 3.9). The first time you run the emulator, you will have to slide the lock to unlock the device (like a real phone). Note that the emulator might be behind Eclipse, so you will have to minimize windows or in some other way bring it to the foreground. The button clicks but does not do anything. For this you need to write code.
Figure 3.9 Initial run of Hello World.