Home > Articles > Programming > Java

This chapter is from the book

3.4. Building the App’s GUI

In this section, we’ll show the precise steps for building the Tip Calculator’s GUI. The GUI will not look like the one shown in Fig. 3.1 until you’ve completed the steps. As you procede through this section, the number of details presented may seem large, but they’re repetitive and you’ll get used to them as you use the IDE.

3.4.1. GridLayout Introduction

This app uses a GridLayout (Fig. 3.3) to arrange views into five rows and two columns. Each cell in a GridLayout can be empty or can hold one or more views, including layouts that contain other views. Views can span multiple rows or columns, though we did not use that capability in this GUI. You can specify a GridLayout’s number of rows and columns in the Properties window.

Fig. 3.3

Fig. 3.3 | Tip Calculator GUI’s GridLayout labeled by its rows and columns.

Each row’s height is determined by the tallest view in that row. Similarly, the width of a column is defined by the widest view in that column. By default, views are added to a row from left to right. As you’ll see, you can specify the exact row and column in which a view is to be placed. We’ll discuss other GridLayout features as we present the GUI-building steps. To learn more about class GridLayout, visit:

http://developer.android.com/reference/android/widget/GridLayout.html

Id Property Values for This App’s Views

Figure 3.4 shows the views’ Id property values. For clarity, our naming convention is to use the view’s class name in the view’s Id property and Java variable name.

Fig. 3.4

Fig. 3.4 | Tip Calculator GUI’s components labeled with their Id property values.

In the right column of the first row, there are actually two components in the same grid cell—the amountDisplayTextView is hiding the amountEditText that receives the user input. As you’ll soon see, we restrict the user’s input to integer digits so that the user cannot enter invalid input. However, we want the user to see the bill amount as a currency value. As the user enters each digit, we divide the amount by 100.0 and display the currency-formatted result in the amountDisplayTextView. In the U.S. locale, if the user enters 3456, as each digit is entered the amountDisplayTextView will show the values $0.03, $0.34, $3.45 and $34.56, respectively.

LinearLayout Id Property Values

Figure 3.5 shows the Ids of the three horizontal LinearLayouts in the GridLayout’s right column.

Fig. 3.5

Fig. 3.5 | Tip Calculator GUI’s LinearLayouts with their Id property values.

3.4.2. Creating the TipCalculator Project

The Android Developer Tools IDE allows only one project with a given name per workspace, so before you create the new project, delete the TipCalculator project that you test-drove in Section 3.2. To do so, right click it and select Delete. In the dialog that appears, ensure that Delete project contents on disk is not selected, then click OK. This removes the project from the workspace, but leaves the project’s folder and files on disk in case you’d like to look at our original app again later.

Creating a New Blank App Project

Next, create a new Android Application Project. Specify the following values in the New Android Project dialog’s first New Android Application step, then press Next >:

  • Application Name: Tip Calculator
  • Project Name: TipCalculator
  • Package Name: com.deitel.tipcalculator
  • Minimum Required SDK: API18: Android 4.3
  • Target SDK: API19: Android 4.4
  • Compile With: API19: Android 4.4
  • Theme: Holo Light with Dark Action Bar
  • Create Activity: TipCalculator
  • Build Target: Ensure that Android 4.3 is checked

In the New Android Project dialog’s second New Android Application step, leave the default settings, then press Next >. In the Configure Launcher Icon step, click the Browse... button, select the DeitelGreen.png app icon image (provided in the images folder with the book’s examples) and click the Open button, then press Next >. In the Create Activity step, select Blank Activity (keep the default activity name), then press Next >. In the Blank Activity step, leave the default settings, then press Finish to create the project. In the Graphical Layout editor, select Nexus 4 from the screen-type drop-down list (as in Fig. 2.12). Once again, we’ll use this device as the basis for our design.

3.4.3. Changing to a GridLayout

The default layout in a Blank App’s GUI is a RelativeLayout. Here, you’ll change that to a GridLayout. First, right click the TextView in the Outline window, then select Delete to remove it from the GUI. Next, right click the RelativeLayout in the Outline window and select Change Layout.... In the Change Layout dialog, select GridLayout and click OK. The IDE changes the layout and sets its Id to GridLayout1. We changed this to gridLayout using the Id field in the Properties window. By default, the GridLayout’s Orientation property is set to horizontal, indicating that its contents will be laid out row-by-row.

Specifying Two Columns and Default Margins for the GridLayout

Recall that the GUI in Fig. 3.3 consists of two columns. To specify this, select gridLayout in the Outline window, then change its Column Count property to 2 (in the Properties window’s GridLayout group). By default, there are no margins—spaces that separate views—around a GridLayout’s cells. Set the GridLayout’s Use Default Margins property to true to indicate that the GridLayout should place margins around its cells. By default, the GridLayout uses the recommended gap between views (8dp), as specified at

http://developer.android.com/design/style/metrics-grids.html

3.4.4. Adding the TextViews, EditText, SeekBar and LinearLayouts

You’ll now build the GUI in Fig. 3.3. You’ll start with the basic layout and views in this section. In Section 3.4.5, you’ll customize the views’ properties to complete the design. As you add each view to the GUI, immediately set its Id property using the names in Figs. 3.43.5. You can change the selected view’s Id via the Properties window or by right clicking the view (in the Graphical Layout editor or Outline window), selecting Edit ID... and changing the Id in the Rename Resource dialog that appears.

In the following steps, you’ll use the Outline window to add views to the GridLayout. When working with layouts, it can be difficult to see the layout’s nested structure and to place views in the correct locations by dragging them onto the Graphical Layout editor window. The Outline window makes these tasks easier because it shows the GUI’s nested structure. Perform the following steps in the exact order specified—otherwise, the views will not appear in the correct order in each row. If this happens, you can reorder views by dragging them in the Outline window.

Step 1: Adding Views to the First Row

The first row consists of the amountTextView in the first column and the amount-EditText behind the amountDisplayTextView in the second column. Each time you drop a view or layout onto the gridLayout in the Outline window, the view is placed in the layout’s next open cell, unless you specify otherwise by setting the view’s Row and Column properties. You’ll do that in this step so that the amount-EditText and amountDisplayTextView are placed in the same cell.

All of the TextViews in this app use the medium-sized font from the app’s theme. The Graphical Layout editor’s Palette provides preconfigured TextViews named Large, Medium and Small (in the Form Widgets section) to represent the theme’s corresponding text sizes. In each case, the IDE configures the TextView’s Text Appearance property accordingly. Perform the following tasks to add the two TextViews and the EditText:

  1. Drag a Medium TextView from the Palette’s Form Widgets section and drop it on the gridLayout in the Outline window. The IDE creates a new TextView named textView1 and nests it in the gridLayout node. The default text "Medium Text" appears in the Graphical Layout editor. Change the TextView’s Id to amountText-View. You’ll change its text in Step 6 (Section 3.4.5).
  2. This app allows you to enter only non-negative integers, which the app divides by 100.0 to display the bill amount. The Palette’s Text Fields section provides many preconfigured EditTexts for various forms of input (e.g., numbers, times, dates, addresses and phone numbers). When the user interacts with an EditText, an appropriate keyboard is displayed based on the EditText’s input type. When you hover over an EditText in the Palette, a tooltip indicates the input type. From the Palette’s Text Fields section, drag a Number EditText (displayed with the number 42 on it) and drop it on the gridLayout node in the Outline window. Change the EditText’s Id to amountEditText. The EditText is placed in the second column of the GridLayout’s first row.
  3. Drag another Medium TextView onto the gridLayout node in the Outline window and change the Id to amountDisplayTextView. The new TextView is initially placed in the first column of the GridLayout’s second row. To place it in the second column of the GridLayout’s first row, set this TextView’s Row and Column properties (located in the Properties window’s Layout Parameters section) to the values 0 and 1, respectively.

Step 2: Adding Views to the Second Row

Next, you’ll add a TextView and SeekBar to the GridLayout. To do so:

  1. Drag a Medium TextView (customPercentTextView) from the Palette’s Form Widgets section onto the gridLayout node in the Outline window.
  2. Drag a SeekBar (customTipSeekBar) from the Palette’s Form Widgets section onto the gridLayout node in the Outline window.

Step 3: Adding Views to the Third Row

Next, you’ll add a LinearLayout containing two TextViews to the GridLayout. To do so:

  1. From the Palette’s Layouts section, drag a Linear Layout (Horizontal) (percentLinearLayout) onto the gridLayout node in the Outline window.
  2. Drag a Medium TextView (percent15TextView) onto the percentLinearLayout node in the Outline window. This nests the new TextView in the LinearLayout.
  3. Drag another Medium TextView (percentCustomTextView) onto the percentLinearLayout node in the Outline window.
  4. The percentLinearLayout and its two nested TextViews should be placed in the second column of the GridLayout. To do so, select the percentLinearLayout in the Outline window, then set its Column property to 1.

Step 4: Adding Views to the Fourth Row

Next, you’ll add a TextView and a LinearLayout containing two more TextViews to the GridLayout. To do so:

  1. Drag a Medium TextView (tipTextView) onto the gridLayout node.
  2. Drag a Linear Layout (Horizontal) (tipLinearLayout) onto the gridLayout node.
  3. Drag two Medium TextViews (tip15TextView and tipCustomTextView) onto the tipLinearLayout node.

Step 5: Adding Views to the Fifth Row

To create the last row of the GUI, repeat Step 4, using the Ids totalTextView, totalLinearLayout, total15TextView and totalCustomTextView.

Reviewing the Layout So Far

The GUI and Outline window should now appear as shown in Fig. 3.6. The warning symbols shown in the Graphical Layout editor and the Outline window will go away as you complete the GUI design in Section 3.4.5.

Fig. 3.6

Fig. 3.6 | The GUI and the IDE’s Outline window after adding all the views to the GridLayout.

3.4.5. Customizing the Views to Complete the Design

You’ll now complete the app’s design by customizing the views’ properties and creating several string and dimension resources. As you learned in Section 2.5, literal string values should be placed in the strings.xml resource file. Similarly, literal numeric values that specify view dimensions (e.g., widths, heights and spacing) should be placed in the dimens.xml resource file.

Step 6: Specifying Literal Text

Specify the literal text for the amountTextView, customPercentTextView, percent-15TextView, percentCustomTextView, tipTextView and totalTextView:

  1. Select the amountTextView in the Outline window.
  2. In the Properties window, click the ellipsis button next to the Text property.
  3. In the Resource Chooser Dialog, click New String....
  4. In the Create New Android String dialog, specify Amount in the String field and amount in the New R.string field, then click OK.
  5. In the Resource Chooser dialog, click OK to set the amountTextView’s Text property to the string resource identified as amount.

Repeat the preceding tasks for the other TextViews using the values shown in Fig. 3.7.

Fig. 3.7

Fig. 3.7 | String resource values and resource IDs.

Step 7: Right Aligning the TextViews in the Left Column

In Fig. 3.3, each of the left column’s TextViews is right aligned. For the amountTextView, customPercentTextView, tipTextView and totalTextView, set the layout Gravity property to right—located in the Layout Parameters section in the Properties window.

Step 8: Configuring the amountTextView’s Label For Property

Generally, each EditText should have a descriptive TextView that helps the user understand the EditText’s purpose (also helpful for accessibility)—otherwise, Android Lint issues a warning. To fix this, you set the TextView’s Label For property to the Id of the associated EditText. Select the amountTextView and set its Label For property (in the Properties window’s View section) to

@+id/amountEditText

The + is required because the TextView is defined before the EditText in the GUI, so the EditText does not yet exist when Android converts the layout’s XML into the GUI.

Step 9: Configuring the amountEditText

In the final app, the amountEditText is hidden behind the amountDisplayTextView and is configured to allow only digits to be entered by the user. Select the amountEditText and set the following properties:

  1. In the Properties window’s Layout Parameters section, set the Width and Height to wrap_content. This indicates that the EditText should be just large enough to fit its content, including any padding.
  2. Remove the layout Gravity value fill_horizontal, leaving the property’s value blank. We’ll discuss fill_horizontal in the next step.
  3. Remove the Ems property’s value, which indicates the EditText’s width, measured in uppercase M characters of the view’s font. In our GridLayout, this causes the second column to be too narrow, so we removed this default setting.
  4. In the Properties window’s TextView section, set Digits to 0123456789—this allows only digits to be entered, even though the numeric keypad contains minus (-), comma (,), period (.) and space buttons. By default, the Digits property is not displayed in the Properties window, because it’s considered to be an advanced property. To display it, click the Show Advanced Properties (showadv.jpg) toggle button at the top of the Properties window.
  5. We restricted the bill amount to a maximum of six digits—so the largest supported bill amount is 9999.99. In the Properties window’s TextView section, set the Max Length property to 6.

Step 10: Configuring the amountDisplayTextView

To complete the formatting of the amountDisplayTextView, select it and set the following properties:

  1. In the Properties window’s Layout Parameters section, set the Width and Height to wrap_content to indicate that the TextView should be large enough to fit its content.
  2. Remove the Text property’s value—we’ll programmatically display text here.
  3. In the Properties window’s Layout Parameters section, set the layout Gravity to fill_horizontal. This indicates that the TextView should occupy all remaining horizontal space in this GridLayout row.
  4. In the View section, set the Background to @android:color/holo_blue_bright. This is one of several predefined colors (each starts with @android:color) in Android’s Holo theme. As you start typing the Background property’s value, a drop-down list of the theme’s available colors is displayed. You can also use any custom color created from a combination of red, green and blue components called RGB values—each is an integer in the range 0–255 that defines the amount of red, green and blue in the color, respectively. Custom colors are defined in hexadecimal (base 16) format, so the RGB components are values in the range 00–FF. Android also supports alpha (transparency) values in the range 0 (completely transparent) to 255 (completely opaque). To use alpha, you specify the color in the format #AARRGGBB, where the first two hexadecimal digits represent the alpha value. If both digits of each color component are the same, you can use the abbreviated formats #RGB or #ARGB. For example, #9AC is treated as #99AACC and #F9AC is treated as #FF99AACC.
  5. Finally, you’ll add some padding around the TextView. To do so, you’ll create a new dimension resource named textview_padding, which you’ll use several times in the GUI. A view’s Padding property specifies space on all sides of the views’s content. In the Properties window’s View section, click the Padding property’s ellipsis button. Click New Dimension... to create a new dimension resource. Specify textview_padding for the Name and 8dp for the Value and click OK, then select your new dimension resource and click OK.

Step 11: Configuring the customPercentTextView

Notice that the customPercentTextView is aligned with the top of the customTipSeekBar’s thumb. This looks better if it’s vertically centered. To do this, in the Properties window’s Layout Parameters section, modify the Gravity value from right to

right|center_vertical

The vertical bar (|) character is used to separate multiple Gravity values—in this case indicating that the TextView should be right aligned and centered vertically within the grid cell. Also set the customPercentTextView’s Width and Height properties to wrap_content.

Step 12: Configuring the customTipSeekBar

By default, a SeekBar’s range is 0 to 100 and its current value is indicated by its Progress property. This app allows custom tip percentages from 0 to 30 and specifies a default of 18. Set the SeekBar’s Max property to 30 and the Progress property to 18. Also, set the Width and Height to wrap_content.

Step 13: Configuring the percent15TextView and percentCustomTextView

Recall that GridLayout does not allow you to specify how a view should be sized relative to other views in a given row. This is why we placed the percent15TextView and percentCustomTextView in a LinearLayout, which does allow proportional sizing. A view’s layout Weight (in certain layouts, such as LinearLayout) specifies the view’s relative importance with respect to other views in the layout. By default, all views have a Weight of 0.

In this layout, we set Weight to 1 for percent-15-Text-View and percentCustomTextView—this indicates that they have equal importance, so they should be sized equally. By default, when we added the percentLinearLayout to the GridLayout, its layout Gravity property was set to fill_horizontal, so the layout occupies the remaining space in the third row. When the LinearLayout is stretched to fill the rest of the row, the TextViews each occupy half of the LinearLayout’s width.

We also wanted each TextView to center its text. To do this, in the Properties window’s TextView section, set the Gravity property to center. This specifies the TextView’s text alignment, whereas the layout Gravity property specifies how a view aligns with respect to the layout.

Step 14: Configuring the tip15TextView, tipCustomTextView, total15TextView and totalCustomTextView

To finalize these four TextViews, perform the following tasks on each:

  1. Select the TextView.
  2. Delete its Text value—we’ll set this programmatically.
  3. Set the Background to @android:color/holo_orange_light.
  4. Set the layout Gravity to center.
  5. Set the layout Weight to 1.
  6. Set the layout Width to 0dp—this allows the layout to use the Weight to determine the view’s width.
  7. Set the TextView Gravity to center.
  8. Set the TextView Padding to @dimen/textview_padding (the dimension resource you created in a previous step).

Notice that there’s no horizontal space between the TextViews in the tipLinearLayout and totalLinearLayout. To fix this, you’ll specify an 8dp right margin for the tip15TextView and total15TextView. In the Properties window’s Layout Parameters section, expand the Margin section, then set the Right margin to 8dp by creating a new dimension resource named textview_margin. Next, use this resource to set the total-15-Text-View’s Right margin.

Step 15: Vertically Centering the tipTextView and totalTextView

To vertically center the tipTextView and totalTextView with the other views in their respective rows, modify their layout Gravity properties from right to

right|center_vertical

When you do this for the totalTextView, the GridLayout centers this component vertically in the remaining space from the fifth row to the bottom of the screen. To fix this problem, drag a Space view (in the Palette’s Layout section) onto the gridLayout node in the Outline window. This creates a sixth row that occupies the rest of the screen. As its name implies, a Space view occupies space in a GUI. The GUI should now appear as in Fig. 3.8.

Fig. 3.8

Fig. 3.8 | Final GUI design.

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