Home > Articles > Programming > Java

This chapter is from the book

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

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
                                                                           //1
    android:layout_width="match_parent"
    android:layout_height="match_parent"
                                                                           //2
    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" >
                                                                           //3
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"/>

</RelativeLayout>
  1. 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.
  2. 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.

  3. 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

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

Figure 3.8 A Small TextView positioned properly on a Graphical Layout.

Listing 3.3 Layout XML with TextView Added

<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=".HelloWorldActivity" >

    <TextView
                                                                           //1
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="@dimen/message_text_size" />

    <TextView
        android:id="@+id/textView1"                                        //2
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"                            //3
        android:layout_below="@+id/textView2"
        android:layout_marginLeft="19dp"                                     //4
        android:layout_marginTop="36dp"
        android:text="Name:"                                               //5
        android:textAppearance="?android:attr/textAppearanceSmall" />        //6

</RelativeLayout>
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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:".
  6. 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

Figure 3.9 Initial run of Hello World.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020