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 | 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:
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 | 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 | 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
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.4–3.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:
- 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).
- 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.
- 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:
- Drag a Medium TextView (customPercentTextView) from the Palette’s Form Widgets section onto the gridLayout node in the Outline window.
- 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:
- From the Palette’s Layouts section, drag a Linear Layout (Horizontal) (percentLinearLayout) onto the gridLayout node in the Outline window.
- Drag a Medium TextView (percent15TextView) onto the percentLinearLayout node in the Outline window. This nests the new TextView in the LinearLayout.
- Drag another Medium TextView (percentCustomTextView) onto the percentLinearLayout node in the Outline window.
- 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:
- Drag a Medium TextView (tipTextView) onto the gridLayout node.
- Drag a Linear Layout (Horizontal) (tipLinearLayout) onto the gridLayout node.
- 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 | 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:
- Select the amountTextView in the Outline window.
- In the Properties window, click the ellipsis button next to the Text property.
- In the Resource Chooser Dialog, click New String....
- In the Create New Android String dialog, specify Amount in the String field and amount in the New R.string field, then click OK.
- 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 | 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
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:
- 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.
- Remove the layout Gravity value fill_horizontal, leaving the property’s value blank. We’ll discuss fill_horizontal in the next step.
- 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.
- 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 () toggle button at the top of the Properties window.
- 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:
- 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.
- Remove the Text property’s value—we’ll programmatically display text here.
- 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.
- 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.
- 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
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:
- Select the TextView.
- Delete its Text value—we’ll set this programmatically.
- Set the Background to @android:color/holo_orange_light.
- Set the layout Gravity to center.
- Set the layout Weight to 1.
- Set the layout Width to 0dp—this allows the layout to use the Weight to determine the view’s width.
- Set the TextView Gravity to center.
- 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
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 | Final GUI design.