Home > Articles > Programming > Java

This chapter is from the book

3.5 Building the Welcome App’s GUI with the ADT’s Visual Layout Editor

Next, you’ll create the GUI for the Welcome app. The ADT’s Visual Layout Editor allows you to build your GUI by dragging and dropping GUI components, such as Buttons, TextViews, ImageViews and more, onto an app. For an Android app that you create with Eclipse, the GUI layout is stored in an XML file called main.xml, by default. Defining the GUI in XML allows you to easily separate your app’s logic from its presentation. Layout files are considered app resources and are stored in the project’s res folder. GUI layouts are placed within that folder’s layout subfolder. When you double click the main.xml file in your app’s /res/layout folder, the Visual Layout Editor view is displayed by default (Fig. 3.7). To view the XML contents of the file (Fig. 3.8), click the tab with the name of the layout file (main.xml in this case). You can switch back to the Visual Layout Editor by clicking the Graphical Layout tab. We’ll present the layout’s XML in Section 3.6.

Fig. 3.7

Fig. 3.7 Visual Layout Editor view of the app’s default GUI.

The Default GUI

The default GUI for a new Android app consists of a LinearLayout with a black background and contains a TextView with the text "Hello World, Welcome!" (Fig. 3.7). A LinearLayout arranges GUI components in a line horizontally or vertically. A TextView allows you to display text. If you were to execute this app in an AVD or on a device, you’d see the default black background and text.

Fig. 3.8

Fig. 3.8 XML view of the app’s default GUI.

Figure 3.9 lists some of the layouts from the android.widget package.1 We’ll cover many more GUI components that can be placed in layouts—for a complete list, visit:

developer.android.com/reference/android/widget/package-summary.html

Fig. 3.9 Android layouts (package android.widget).

Layout

Description

FrameLayout

Allocates space for a single component. You can add more than one component to this layout, but each will be displayed from the layout’s upper-left corner. The last component added will appear on top.

LinearLayout

Arranges components horizontally in one row or vertically in one column.

RelativeLayout

Arranges components relative to one another or relative to their parent container.

TableLayout

Arranges components into a table of rows. You can then use the TableRow layout (a subclass of LinearLayout) to organize the columns.

Configuring the Visual Layout Editor to use the Appropriate Android SDK

If you’ve installed multiple Android SDKs, the ADT Plugin selects the most recent one as the default for design purposes in the Graphical Layout tab—regardless of the SDK you selected when you created the project. In Fig. 3.7, we selected Android 2.3.3 from the SDK selector drop-down list at the top-right side of the Graphic Layout tab to indicate that we’re designing a GUI for an Android 2.3.3 device.

Deleting and Recreating the main.xml File

For this application, you’ll replace the default main.xml file with a new one that uses a RelativeLayout, in which components are arranged relative to one another. Perform the following steps to replace the default main.xml file:

  1. Make sure main.xml is closed, then right click it in the project’s /res/layout folder and select Delete to delete the file.
  2. Right click the layout folder and select New > Other... to display the New dialog.
  3. In the Android node, select Android XML File and click Next > to display the New Android XML File dialog.
  4. Configure the file name, location and root layout for the new main.xml file as shown in Fig. 3.10, then click Finish.
    Fig. 3.10

    Fig. 3.10 Creating a new main.xml file in the New Android XML File dialog.

Configuring the Visual Layout Editor’s Size and Resolution

Figure 3.11 shows the new main.xml file in the Visual Layout Editor. Android runs on a wide variety of devices, so the Visual Layout Editor comes with several device configurations that represent various screen sizes and resolutions. These can be selected from the Device Configurations drop-down list at the top-left side of the Graphic Layout tab (Fig. 3.11). If these predefined configurations do not match the device you wish to target, you can create your own device configurations from scratch, or by copying and modifying the existing ones.

Fig. 3.11

Fig. 3.11 Visual Layout Editor view of the app’s default GUI.

Our primary testing device for this book was the Samsung Nexus S, which has a 4-inch screen with 480-by-800 (WVGA) resolution. When designing an Android GUI, you typically want it to be scalable so that it displays properly on various devices. For this reason, the Visual Layout Editor’s design area does not need to precisely match your actual device’s. Instead, you can choose a similar device configuration. In Fig. 3.11, we selected the 3.7in WVGA (Nexus One) option—this device has the same WVGA resolution as the Nexus S, but a slightly smaller screen size. Many of today’s smartphones have 480-by-800 or 480-by-854 resolution.

Images and Screen Sizes/Resolutions

Because Android devices have various screen sizes, resolutions and pixel densities (that is, dots per inch or DPI), Android allows you to provide separate images (and other resources) that the operating system chooses based on the actual device’s pixel density. For this reason your project’s res folder contains three subfolders for images—drawable-hdpi (high density), drawable-mdpi (medium density) and drawable-ldpi (low density). These folders store images with different pixel densities (Fig. 3.12).

Fig. 3.12 Android pixel densities.

Density

Description

ldpi

Low density—approximately 120 dots-per-inch.

mdpi

Medium density—approximately 160 dots-per-inch.

hdpi

High density—approximately 240 dots-per-inch.

xhdpi

Extra high density—approximately 320 dots-per-inch.

nodpi

Indicates that a resource should not be scaled regardless of screen density.

Images for devices that are similar in pixel density to our testing device are placed in the folder drawable-hdpi. Images for medium- and low-density screens are placed in the folders drawable-mdpi and drawable-ldpi, respectively. As of Android 2.2, you can also add a drawable-xhdpi subfolder to the app’s res folder to represent screens with extra high pixel densities. Android will scale images up and down to different densities as necessary.

Step 1: Adding Images to the Project

You’ll now begin designing the Welcome app. In this chapter, we’ll use the Visual Layout Editor and the Outline window to build the app, then we’ll explain the generated XML in detail. In subsequent chapters, we’ll also edit the XML directly.

For this app, you’ll need to add the Deitel bug image (bug.png) and the Android logo image (android.png) to the project—we’ve provided these in the images folder with the book’s examples. Perform the following steps to add the images to this project:

  1. In the Package Explorer window, expand the project’s res folder.
  2. Locate and open the images folder provided with the book’s examples, then drag the images in the folder onto the res folder’s drawable-hdpi subfolder.

These images can now be used in the app.

Step 2: Changing the Id Property of the RelativeLayout

You can use the Properties window to configure the properties of the selected layout or component without editing the XML directly. If the Properties window is not displayed, you can display it by double clicking the RelativeLayout in the Outline window. You can also select Window > Show View > Other..., then select Properties from the General node in the Show View dialog. To select a layout or component, you can either click it in the Visual Layout Editor or select its node in the Outline window (Fig. 3.13). The Properties window cannot be used when the layout is displayed in XML view.

Fig. 3.13

Fig. 3.13 Hierarchical GUI view in the Outline window.

You should rename each layout and component with a relevant name, especially if the the layout or component will be manipulated programmatically (as we’ll do in later apps). Each object’s name is specified via its Id property. The Id can be used to access and modify component without knowing its exact location in the XML. As you’ll see shortly, the id can also be used to specify the relative positioning of components in a RelativeLayout.

Select the RelativeLayout, then scroll to the Id property in the Properties window and set its value to

@+id/welcomeRelativeLayout

The + in the syntax @+id indicates that a new id (that is, a variable name) should be created with the identifier to the right of the /. The Properties and Outline windows should now appear as in Fig. 3.14.

Fig. 3.14

Fig. 3.14 Properties window after changing the RelativeLayout’s Id property.

Step 3: Changing the Background Property of the RelativeLayout

The layout’s default background color is black, but we’d like it to be white. Every color can be created from a combination of red, green and blue components called RGB values—each is an integer in the range 0–255. The first value defines the amount of red in the color, the second the amount of green and the third the amount of blue. When using the IDE to specify a color you typically use hexadecimal format. In this case, the RGB components are represented as values in the range 00–FF.

To change the background color, locate the Background property in the Properties window and set its value to #FFFFFF (Fig. 3.15). This represents white in the hexadecimal format #RRGGBB—the pairs of hexadecimal digits represent the red, green and blue color components, respectively. Android also supports alpha (transparency) values in the range 0–255, where 0 represents completely transparent and 255 represents completely opaque. If you wish to use alpha values, you can specify the color in the format #AARRGGBB, where the first two hexadecimal digits represent the alpha value. For cases in which both digits of each component of the color are the same, you can use the formats #RGB or #ARGB. For example, #FFF will be treated as #FFFFFF.

Fig. 3.15

Fig. 3.15 Properties window after changing the RelativeLayout’s Background property.

Step 4: Adding a TextView

Next, we’ll add a TextView to the user interface. In the Form Widgets list at the left of the Visual Layout Editor window, locate TextView and drag it onto the design area (Fig. 3.16). When you add a new component to the user interface, it’s automatically selected and its properties are displayed in the Properties window.

Fig. 3.16

Fig. 3.16 TextView with its default text.

Step 5: Configuring the TextView’s Text Property Using a String Resource

According to the Android documentation for application resources

developer.android.com/guide/topics/resources/index.html

it’s considered a good practice to “externalize” strings, string arrays, images, colors, font sizes, dimensions and other app resources so that you, or someone else on your team, can manage them separately from your application’s code. For example, if you externalize color values, all components that use the same color can be updated to a new color simply by changing the color value in a central resource file.

If you wish to localize your app in several different languages, storing the strings separately from the app’s code allows you to change them easily. In your project’s res folder, the subfolder values contains a strings.xml file that’s used to store strings. To provide localized strings for other languages, you can create separate values folders for each language. For example, the folder values-fr would contain a strings.xml file for French and values-es would contain a strings.xml file for Spanish. You can also name these folders with region information. For example, values-en-rUS would contain a strings.xml file for U.S. English and values-en-rGB would contain a strings.xml file for United Kingdom English. For more information on localization, see

developer.android.com/guide/topics/resources/
   providing-resources.html#AlternativeResources
developer.android.com/guide/topics/resources/localization.html

To set the TextView’s Text property, we’ll create a new string resource in the strings.xml file.

  1. Ensure that the TextView is selected.
  2. Locate its Text property in the Properties window, click its default value, then click the ellipsis button (ellipsis-icon.jpg) at the right size of the property’s value field to display the Resource Chooser dialog.
  3. In the Resource Chooser dialog, click the New String... button to display the Create New Android String dialog (Fig. 3.17).
    Fig. 3.17

    Fig. 3.17 Create New Android String window.

  4. Fill the String and New R.string fields as shown in Fig. 3.17, then click OK to dismiss the Create New Android String dialog and return to the Resource Chooser dialog.
  5. The new string resource named welcome is automatically selected. Click OK to select this resource.

In the Properties window, the Text property should now appear as shown in Fig. 3.18. The syntax @string indicates that an existing string resource will be selected from the strings.xml file, and the name welcome indicates which string resource to select.

Fig. 3.18

Fig. 3.18 Properties window after changing the TextView’s Text property.

A key benefit of defining your string values this way is that you can easily localize your app by creating additional XML resource files for string resources in other languages. In each file, you use the same name in the New R.string field and provide the internationalized string in the String field. Android can then choose the appropriate resource file based on the device user’s preferred language. For more information on localization, visit

developer.android.com/guide/topics/resources/localization.html

Step 6: Configuring the TextView’s Text size and Padding top Properties—Scaled Pixels and Density-Independent Pixels

The sizes of GUI components and text in Android can be specified in several different units (Fig. 3.19). The documentation for supporting multiple screen sizes

developer.android.com/guide/practices/screens_support.html

Fig. 3.19 Measurement units.

Unit

Description

px

pixel

dp or dip

density-independent pixel

sp

scale-independent pixel

in

inches

mm

millimeters

recommends that you use density-independent pixels for the dimensions of GUI components and other screen elements and scale-independent pixels for font sizes.

Defining your GUIs with density-independent pixels enables the Android platform to automatically scale the GUI, based on the pixel density of the actual device’s screen.

One density-independent pixel is equivalent to one pixel on a screen with 160 dpi (dots per inch). On a screen with 240 dpi, each density-independent pixel will be scaled by a factor of 240/160 (i.e., 1.5). So, a component that’s 100 density-independent pixels wide will be scaled to 150 actual pixels wide. On a screen with 120 dpi, each density-independent pixel is scaled by a factor of 120/160 (i.e., .75). So, the same component that’s 100 density-independent pixels wide will be 75 actual pixels wide. Scale-independent pixels are scaled like density-independent pixels, and they’re also scaled by the user’s preferred font size specified on the device. [Note: At the time of this writing, users cannot yet change the preferred font size on Android devices, but this feature is expected in the future.]

You’ll now increase the size of the TextView’s font and add some padding above the TextView to separate the text from the edge of the device’s screen.

  1. To change the font size, ensure that the TextView is selected, then change its Text size property to 40sp.
  2. To add some space between the top edge of the layout and the TextView, set the Layout margin top property in the Misc section of the Properties window to 10dp.

Step 7: Configuring Additional TextView Properties

Configure the following additional TextView’s properties as well:

  1. Set its Id property to @+id/welcomeTextView.
  2. Set its Text color property to #00F (blue).
  3. Set its Text style property to bold. To do so, click the Value field for this property, then click the ellipsis button (ellipsis-icon.jpg) to display the dialog for selecting the font style. Click the bold checkbox, then click OK to set the text style.
  4. To center the text in the TextView if it wraps to multiple lines, set its Gravity property to center. To do so, click the Value field for this property, then click the ellipsis button to display a dialog with the Gravity property’s options (Fig. 3.20). Click the center checkbox, then click OK to set the value.
    Fig. 3.20

    Fig. 3.20 Options for the gravity attribute of an object.

The Visual Layout Editor window should now appear as shown in Fig. 3.21.

Fig. 3.21

Fig. 3.21 Visual Layout Editor window after completing the TextView’s configuration.

Step 8: Adding ImageViews to Display the Android Logo and the Deitel Bug Logo

Next, you’ll add two ImageViews to the GUI to display the images that you added to the project in Step 1. When you first drag an ImageView onto the Visual Layout Editor, nothing appears. For this reason, we’ll use the Outline window to add the ImageViews. Perform the following steps:

  1. Drag an ImageView from the Images & Media category in the Visual Layout Editor’s Palette and drop it onto the Outline window as shown in Fig. 3.22. The new ImageView appears below the welcomeTextView node. This does not indicate that this component will appear below the TextView in the GUI. This requires setting the Layout below property, which we’ll do in a moment. [Note: If you drag the ImageView over the welcomeTextView and hover for a moment, a green rectangle with sections will appear around the welcomeTextView. If you then drag the ImageView over one of those sections and drop it, the Visual Layout Editor can set the relative positioning for you.]

    Fig. 3.22

    Fig. 3.22 Dragging and dropping an ImageView onto the Outline window.

  2. Set the ImageView’s Id property to @+id/droidImageView. The Outline window now shows the object’s name as droidImageView.
  3. Set the droidImageView’s Layout below property to @id/welcomeTextView to position the ImageView below the welcomeTextView. To do so, click the Value field for this property, then click the ellipsis button to display the Reference Chooser dialog (Fig. 3.23). The ID node contains the names of the objects in the GUI. Expand the ID node and select welcomeTextView.
    Fig. 3.23

    Fig. 3.23 Selecting the value for the droidImageView’s Layout below property.

  4. Set the droidImageView’s Layout center horizontal property to true to center the ImageView in the layout.
  5. Set the droidImageView’s Src property to the image that should be displayed. To do so, click the Value field for this property, then click the ellipsis button to display the Reference Chooser dialog (Fig. 3.24). The Drawable node contains the resources in your app’s drawable folders within the res folder. In the dialog, expand the Drawable node and select android, which represents the android.png image.
    Fig. 3.24

    Fig. 3.24 Selecting the value for the droidImageView’s Src property.

  6. Repeat items 1–5 above to create the bugImageView. For this component, set its Id property to @+id/bugImageView, its Src property to bug and its Layout below property to droidImageView.

The Visual Layout Editor window should now appear as shown in Fig. 3.25.

Fig. 3.25

Fig. 3.25 Visual Layout Editor window after completing the GUI configuration.

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