Question

CIT 238 – Android Programming I Tip Calculator Create an app that will compute the tip...

CIT 238 – Android Programming I Tip Calculator Create an app that will compute the tip on a restaurant bill. App should contain: • An EditText to allow the user to enter the total amount of the bill • RadioButtons to allow the user to select one of the given tip percentages o 10% tip o 15% tip o 20% tip • A Button to calculate the amount of the tip. • A TextView to display the tip amount (tip only, not bill + tip) To retrieve input from an EditText: String variableName = nameOfEditText.getText().toString(); NOTE: EditText input is ALWAYS returned as a string. You must convert the input to another data type if you wish to use the input for calculations. To display text in a TextView: nameOfTextView.setText("Text to display");

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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 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. Close MainActivity.java and fragment_main.xml, then open activity_main.xml. In the Graphical Layout editor, select Nexus 4 from the screen-type drop-down list.

Changing to a GridLayout

The default layout in activity_main.xml is a FrameLayout. Here, you’ll change that to a GridLayout. 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. Ensure that the GridLayout’s Padding Left and Padding Right properties are set to activity_horizontal_margin and that the Padding Top and Padding Bottom properties are set to activity_vertical_margin.

Adding TextViews, EditText, SeekBars and LinearLayouts

You’ll start with the basic layout and views in this section. As you add each view to the GUI, immediately set its Id property . 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 amountEditText 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 amountEditText 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 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 amountTextView. You’ll change its text in Step 6 .

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 the Following figure. The warning symbols shown in the Graphical Layout editor and the Outline window will go away as you complete the GUI design

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. 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, percent15TextView, 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 the folloing Figure

Step 7: Right Aligning the TextViews in the Left Column

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

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 ( ) 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 dropdown 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 percent15TextView 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 total15TextView’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.

Final GUI design.

Adding Functionality to the App

Class MainActivity implements the Tip Calculator app’s functionality. It calculates the 15% and custom percentage tips and total bill amounts, and displays them in locale-specific currency format. To view the file, open src/com.deitel/tipcalculator and double clck MainActivity.java.

The package and import Statements shows the package statement and import statements in MainActivity.java. The package statement in line 3 was inserted when you created the project. When you open a Java file in the IDE, the import statements are collapsed—one is displayed with a + to its left. You can click the + to see the complete list of import statements.

1 // MainActivity.java

2 // Calculates bills using 15% and custom percentage tips.

3 package com.deitel.tipcalculator;

4

5 import java.text.NumberFormat; // for currency formatting

6

7 import android.app.Activity; // base class for activities

8 import android.os.Bundle; // for saving state information

9 import android.text.Editable; // for EditText event handling

10 import android.text.TextWatcher; // EditText listener

11 import android.widget.EditText; // for bill amount input

12 import android.widget.SeekBar; // for changing custom tip percentage

13 import android.widget.SeekBar.OnSeekBarChangeListener; // SeekBar listener

14 import android.widget.TextView; // for displaying text

15

Lines 5–14 import the classes and interfaces the app uses:

• Class NumberFormat of package java.text (line 5) provides numeric formatting capabilities, such as locale-specific currency and percentage formats.

• Class Activity of package android.app (line 7) provides the basic lifecycle methods of an app—we’ll discuss these shortly.

• Class Bundle of package android.os (line 8) represents an app’s state information. Android gives an app the opportunity to save its state before another app appears on the screen. This might occur, for example, when the user launches another app or receives a phone call. The app that’s currently on the screen at a given time is in the foreground (the user can interact with it, and the app consumes the CPU) and all other apps are in the background (the user cannot interact with them, and they’re typically not consuming the CPU). When another app comes into the foreground, the app that was previously in the foreground is given the opportunity to save its state as it’s sent to the background.

• Interface Editable of package android.text (line 9) allows you to modify the content and markup of text in a GUI.

• You implement interface TextWatcher of package android.text (line 10) to respond to events when the user changes the text in an EditText.

• Package android.widget (lines 11–14) contains the widgets (i.e., views) and layouts that are used in Android GUIs. This app uses EditText (line 11), SeekBar (line 12) and TextView (line 14) widgets.

• You implement interface SeekBar.OnSeekBarChangeListener of package android.widget (line 13) to respond to the user moving the SeekBar’s thumb.

As you write code with various classes and interfaces, you can use the IDE’s Source > Organize Imports command to let the IDE insert the import statements for you. For cases in which the same class or interface name appears in more than one package, the IDE will let you select the appropriate import statement.

Tip Calculator App Activity and the Activity Lifecycle

Class MainActivity is the Tip Calculator app’s Activity subclass. When you created the TipCalculator project, the IDE generated this class as a subclass of Activity and provided an override of class Activity’s inherited onCreate method . Every Activity subclass must override this method. The default code for class MainActivity also included an onCreateOptionsMenu method, which we removed because it’s not used in this app.

Class MainActivity is a subclass of Activity.

16 // MainActivity class for the Tip Calculator app

17 public class MainActivity

18 {

Class Variables and Instance Variables

Lines 20–32 of declare class MainActivity’s variables. The NumberFormat objects (lines 20–23) are used to format currency values and percentages, respectively. NumberFormat static method getCurrencyInstance returns a NumberFormat object that formats values as currency using the device’s default locale. Similarly, static method getPercentInstance formats values as percentages using the device’s default locale.

19 // currency and percent formatters

20 private static final NumberFormat currencyFormat =

21 NumberFormat.getCurrencyInstance();

22 private static final NumberFormat percentFormat =

23 NumberFormat.getPercentInstance();

24

25 private double billAmount = 0.0; // bill amount entered by the user

26 private double customPercent = 0.18; // initial custom tip percentage

27 private TextView amountDisplayTextView; // shows formatted bill amount

28 private TextView percentCustomTextView; // shows custom tip percentage

29 private TextView tip15TextView; // shows 15% tip

30 private TextView total15TextView; // shows total with 15% tip

31 private TextView tipCustomTextView; // shows custom tip amount

32 private TextView totalCustomTextView; // shows total with custom tip

The bill amount entered by the user into amountEditText will be read and stored as a double in billAmount (line 25). The custom tip percentage (an integer in the range 0– 30) that the user sets by moving the Seekbar thumb will be multiplied by 0.01 to create a double for use in calculations, then stored in customPercent (line 26). For example, if you select 25 with the SeekBar, customPercent will store 0.25, so the app will multiply the bill amount by 0.25 to calculate the 25% tip.

Line 27 declares the TextView that displays the currency-formatted bill amount. Line 28 declares the TextView that displays the custom tip percentage based on the SeekBar thumb’s position. The variables in line 29–32 will refer to the TextViews in which the app displays the calculated tips and totals.

Overriding Method onCreate of Class Activity

The onCreate method —which is auto-generated with lines 38–39 when you create the app’s project—is called by the system when an Activity is started. Method onCreate typically initializes the Activity’s instance variables and views. This method should be as simple as possible so that the app loads quickly. In fact, if the app takes longer than five seconds to load, the operating system will display an ANR (Application Not Responding) dialog—giving the user the option to forcibly terminate the app.

34 // called when the activity is first created

35 @Override

36 protected void onCreate(Bundle savedInstanceState)

37 {

38 super.onCreate(savedInstanceState); // call superclass's version

39 setContentView(R. layout.activity_main); // inflate the GUI

40

41 // get references to the TextViews

42 // that MainActivity interacts with programmatically

43 amountDisplayTextView =

44 (TextView) findViewById(R.id.amountDisplayTextView);

45 percentCustomTextView =

46 (TextView) findViewById(R.id.percentCustomTextView);

47 tip15TextView = (TextView) findViewById(R.id.tip15TextView);

48 total15TextView = (TextView) findViewById(R.id.total15TextView);

49 tipCustomTextView = (TextView) findViewById(R.id.tipCustomTextView);

50 totalCustomTextView =

51 (TextView) findViewById(R.id.totalCustomTextView);

52

53 // update GUI based on billAmount and customPercent

54 amountDisplayTextView.setText(

55 currencyFormat.format(billAmount));

56 updateStandard(); // update the 15% tip TextViews

57 updateCustom(); // update the custom tip TextViews

58

59 // set amountEditText's TextWatcher

60 EditText amountEditText =

61 (EditText) findViewById(R.id.amountEditText);

62 amountEditText.addTextChangedListener(amountEditTextWatcher);

63

64 // set customTipSeekBar's OnSeekBarChangeListener

65 SeekBar customTipSeekBar =

66 (SeekBar) findViewById(R.id.customTipSeekBar);

67 customTipSeekBar.setOnSeekBarChangeListener(customSeekBarListener);

68 } // end method onCreate

69

onCreate’s Bundle Parameter

During the app’s execution, the user could change the device’s configuration by rotating the device or sliding out a hard keyboard. For a good experience, the app should continue operating smoothly through such configuration changes. When the system calls onCreate, it passes a Bundle argument containing the Activity’s saved state, if any. Typically, you save state in Activity methods onPause or onSaveInstanceState (demonstrated in later apps). Line 38 calls the superclass’s onCreate method, which is required when overriding onCreate.

Generated R Class Contains Resource IDs

As you build your app’s GUI and add resources (such as strings in the strings.xml file or views in the activity_main.xml file) to your app, the IDE generates a class named R that contains nested classes representing each type of resource in your project’s res folder. You can find this class in your project’s gen folder, which contains generated source-code files. The nested classes are declared static, so that you can access them in your code with R.ClassName. Within class R’s nested classes, the IDE creates static final int constants that enable you to refer to your app’s resources programmatically from your code (as we’ll discuss momentarily). Some of the nested classes in class R include:

• class drawable—contains constants for any drawable items, such as images, that you put in the various drawable folders in your app’s res folder

• class id—contains constants for the views in your XML layout files

• class layout—contains constants that represent each layout file in your project (such as, activity_main.xml)

• class string—contains constants for each String in the strings.xml file.

Inflating the GUI The call to setContentView (line 39) receives the constant R.layout.activity_main to indicate which XML file represents MainActivity’s GUI—in this case, the constant represents the main.xml file. Method setContentView uses this constant to load the corresponding XML document, which is then parsed and converted into the app’s GUI. This process is known as inflating the GUI.

Getting References to the Widgets

Once the layout is inflated, you can get references to the individual widgets so that you can interact with them programmatically. To do so, you use class Activity’s findViewById method. This method takes an int constant representing a specific view’s Id and returns a reference to the view. The name of each view’s R.id constant is determined by the component’s Id property that you specified when designing the GUI. For example, amountEditText’s constant is R.id.amountEditText.

Lines 43–51 obtain references to the TextViews that are changed by the app. Lines 43–44 obtain a reference to the amountDisplayTextView that’s updated when the user enters the bill amount. Lines 45–46 obtain a reference to the percentCustomTextView that’s updated when the user changes the custom tip percentage. Lines 47–51 obtain references to the TextViews where the calculated tips and totals are displayed.

Displaying Initial Values in the TextViews

Lines 54–55 set amountDisplayTextView’s text to the initial billAmount (0.00) in a localespecific currency format by calling the currencyFormat object’s format method. Next, lines 56–57 call methods updateStandard and updateCustom to display initial values in the tip and total TextViews.

Registering the Event Listeners

Lines 60–61 get a reference to the amountEditText, and line 62 calls its addTextChangedListener method to register the TextChangedListener that will respond to events generated when the user changes the text in the EditText. We define this listener as an anonymous-inner-class object that’s assigned to the instance variable amountEditTextWatcher. Lines 65–66 get a reference to the customTipSeekBar and line 67 calls its setOnSeekBarChangeListener method to register the OnSeekBarChangeListener that will respond to events generated when the user moves the customTipSeekBar’s thumb to change the custom tip percentage. We define this listener as an anonymous-inner-class object that’s assigned to the instance variable customSeekBarListener.

Method updateStandard of Class MainActivity

Method updateStandard updates the 15% tip and total TextViews each time the user changes the bill amount. The method uses the billAmount value to calculate the tip amount and the total of the bill amount and tip. Lines 78–79 display the amounts in currency format.

Method updateStandard calculates and displays the 15% tip and total.

70 // updates 15% tip TextViews

71 private void updateStandard()

72 {

73 // calculate 15% tip and total

74 double fifteenPercentTip = billAmount * 0.15;

75 double fifteenPercentTotal = billAmount + fifteenPercentTip;

76

77 // display 15% tip and total formatted as currency

78 tip15TextView.setText(currencyFormat.format(fifteenPercentTip));

79 total15TextView.setText(currencyFormat.format(fifteenPercentTotal));

80 } // end method updateStandard

81

Method updateCustom of Class MainActivity

Method updateCustom updates the custom tip and total TextViews based on the tip percentage the user selected with the customTipSeekBar. Line 86 sets the percentCustomTextView’s text to the customPercent value formatted as a percentage. Lines 89– 90 calculate the customTip and customTotal. Then, lines 93–94 display the amounts in currency format.

Method updateCustom calculates and displays the custom tip and total.

82 // updates the custom tip and total TextViews

83 private void updateCustom()

84 {

85 // show customPercent in percentCustomTextView formatted as %

86 percentCustomTextView.setText(percentFormat.format(customPercent));

87

88 // calculate the custom tip and total

89 double customTip = billAmount * customPercent;

90 double customTotal = billAmount + customTip;

91

92 // display custom tip and total formatted as currency

93 tipCustomTextView.setText(currencyFormat.format(customTip));

94 totalCustomTextView.setText(currencyFormat.format(customTotal));

95 } // end method updateCustom

96

Anonymous Inner Class That Implements Interface OnSeekBarChangeListener

Lines 98–120 create the anonymous-inner-class object named customSeekBarListener that responds to customTipSeekBar’s events.

Line 67 registered customSeekBarListener as customTipSeekBar’s OnSeekBarChangeListener event-handling object. For clarity, we define all but the simplest event-handling objects in this manner so that we do not clutter the onCreate method with this code.

Anonymous inner class that implements interface OnSeekBarChangeListener to respond to the events of the customSeekBar

97 // called when the user changes the position of SeekBar

98 private OnSeekBarChangeListener customSeekBarListener =

99 new OnSeekBarChangeListener()

100 {

101 // update customPercent, then call updateCustom

102 @Override

103 public void onProgressChanged(SeekBar seekBar, int progress,

104 boolean fromUser)

105 {

106 // sets customPercent to position of the SeekBar's thumb

107 customPercent = progress / 100.0;

108 updateCustom(); // update the custom tip TextViews

109 } // end method onProgressChanged

110

111 @Override

112 public void onStartTrackingTouch(SeekBar seekBar)

113 {

114 } // end method onStartTrackingTouch

115

116 @Override

117 public void onStopTrackingTouch(SeekBar seekBar)

118 {

119 } // end method onStopTrackingTouch

120 }; // end OnSeekBarChangeListener

121

Overriding Method onProgressChanged of Interface OnSeekBarChangeListener

Lines 102–119 implement interface OnSeekBarChangeListener’s methods. Method onProgressChanged is called whenever the SeekBar’s thumb position changes. Line 107 calculates customPercent using the method’s progress parameter—an int representing the SeekBar’s thumb position. We divide this by 100.0 to get the custom percentage. Line 108 calls method updateCustom to recalculate and display the custom tip and total.

Overriding Methods onStartTrackingTouch and onStopTrackingTouch of Interface OnSeekBarChangeListener

Java requires that you override every method in an interface that you implement. This app does not need to know when the user starts moving the slider’s thumb (onStartTrackingTouch) or stops moving it (onStopTrackingTouch), so we simply provide an empty body for each (lines 111–119) to fulfill the interface contract.

Anonymous Inner Class That Implements Interface TextWatcher

Lines 123–156 of Fig. 3.16 create the anonymous-inner-class object amountEditTextWatcher that responds to amountEditText’s events. Line 62 registered this object to listen for amountEditText’s events that occur when the text changes.

Overriding Method onTextChanged of Interface TextWatcher

The onTextChanged method (lines 126–144) is called whenever the text in the amountEditText is modified. The method receives four parameters.

122 // event-handling object that responds to amountEditText's events

123 private TextWatcher amountEditTextWatcher = new TextWatcher()

124 {

125 // called when the user enters a number

126 @Override

127 public void onTextChanged(CharSequence s, int start,

128 int before, int count)

129 {

130 // convert amountEditText's text to a double

131 try

132 {

133 billAmount = Double.parseDouble(s.toString()) / 100.0;

134 } // end try

135 catch (NumberFormatException e)

136 {

137 billAmount = 0.0; // default if an exception occurs

138 } // end catch

139

140 // display currency formatted bill amount

141 amountDisplayTextView.setText(currencyFormat.format(billAmount));

142 updateStandard(); // update the 15% tip TextViews

143 updateCustom(); // update the custom tip TextViews

144 } // end method onTextChanged

145

146 @Override

147 public void afterTextChanged(Editable s)

148 {

149 } // end method afterTextChanged

150

151 @Override

152 public void beforeTextChanged(CharSequence s, int start, int count,

153 int after)

154 {

155 } // end method beforeTextChanged

156 }; // end amountEditTextWatcher

157 } // end class MainActivity

In this example, we use only CharSequence s, which contains a copy of amountEditText’s text. The other parameters indicate that the count characters starting at start replaced previous text of length before. Line 133 converts the user input from amountEditText to a double. We allow users to enter only whole numbers in pennies, so we divide the converted value by 100.0 to get the actual bill amount—e.g., if the user enters 2495, the bill amount is 24.95. Lines 142– 143 call updateStandard and updateCustom to recalculate and display the tips and totals.

Other Methods of the amountEditTextWatcher TextWatcher

This app does not need to know what changes are about to be made to the text (beforeTextChanged) or that the text has already been changed (afterTextChanged), so we simply override each of these TextWatcher interface methods with an empty body (lines 146–155) to fulfill the interface contract.

AndroidManifest.xml

you’ll modify the AndroidManifest.xml file to specify that this app’s Activity supports only a device’s portrait orientation and that the soft keypad should always remain on the screen. You’ll use the IDE’s Android Manifest editor to specify these settings. To open the Android Manifest editor, double click the app’s AndroidManifest.xml file in the Package Explorer. At the bottom of the editor, click the Application tab , then select the MainActivity node in the Application Nodes section at the bottom of the window. This displays settings for the MainActivity in the Attributes for com.deitel.tipcalculator.MainActivity section.

Configuring MainActivity for Portrait Orientation In general, most apps should support both portrait and landscape orientations. In portrait orientation, the device’s height is greater than its width. In landscape orientation, the device’s width is greater than its height. In the Tip Calculator app, rotating the device to landscape orientation on a typical phone would cause the numeric keypad to obscure most of the Tip Calculator’s GUI. For this reason, you’ll configure MainActivity to support only portrait orientation. In the Android Manifest editor’s Attributes for com.deitel.tipcalculator.MainActivity section, scroll down to the Screen orientation option and select portrait.

Forcing the Soft Keypad to Always Display for MainActivity

In the Tip Calculator app, the soft keypad should be displayed immediately when the app executes and should remain on the screen at all times. In the Android Manifest editor’s Attributes for com.deitel.tipcalculator.MainActivity section, scroll down to the Window soft input mode option and select stateAlwaysVisible. Note that this will not display the soft keyboard if a hard keyboard is present.

Add a comment
Know the answer?
Add Answer to:
CIT 238 – Android Programming I Tip Calculator Create an app that will compute the tip...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need a help with this app. when I run this app, it is stopped. Here a...

    Need a help with this app. when I run this app, it is stopped. Here a source code for Tip calculator application. activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFF" android:id="@+id/tableLayout" android:stretchColumns="1,2,3" android:padding="5dp"> <!-- tableRow0 --> <TableRow android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/tableRow0"> <TextView android:id="@+id/billTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/billTotal" android:textColor="#000" android:gravity="right" android:paddingRight="5dp"> </TextView> <EditText android:layout_width="wrap_content" android:id="@+id/billEditText" android:layout_height="wrap_content" android:layout_span="3" android:inputType="numberDecimal" android:layout_weight="1"> </EditText> </TableRow> <!-- tableRow1 --> <TableRow android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/tableRow1"> <TextView android:id="@+id/tenTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="10%" android:textColor="#000" android:layout_column="1"...

  • Hi, I am trying to create a simple android app using spinners. It need not be...

    Hi, I am trying to create a simple android app using spinners. It need not be very complex. The app should allow the user to use a simple spinner to select a team from the following list of teams (Kansas City Chiefs, New England Patriots, New Orleans Saints, and the Los Angeles Rams), once the user selects the team they wish to view, the app should display a small paragraph of information (hardcoded) To the screen for the user to...

  • 1. Need help with a Java application that will compute tip amounts based on user input....

    1. Need help with a Java application that will compute tip amounts based on user input. Please let me know what else my code could use. My code is below and I need help formatting the output and calculating the amount paid by each person. Your application will: ask the user for a restaurant name, a waiter/waitress name, a bill amount and the number of people splitting the bill calculate 10%, 15% and 20% tips on the bill amount calculate...

  • Java programming Create a simple tip calculator called TipCalcMethod. Your program should read in the bill...

    Java programming Create a simple tip calculator called TipCalcMethod. Your program should read in the bill amount from the command-line, then show 3 tip amounts: 15%, 20% and 25% of the bill. Don't worry about rounding the result to two decimal places, but make sure that the result includes cents (not just dollars). This program will be different than your first Tipcalc program because you will writea method to calculate the tip amount. program will have 2 methods: main) and...

  • The programming language is C# we are using wpf forms. Hello, I would like to get...

    The programming language is C# we are using wpf forms. Hello, I would like to get my clear button to work. So when clear is click everything is clear not only the total, tax or subtotal but also the combox and the data grid. For the Delete button if the user selects a specific item it will be deleted and for the receipt button, it should create a pdf that contains the Name, Price, quantity, tax, total and subtotal. it...

  • This is done in c programming and i have the code for the programs that it wants at the bottom i ...

    This is done in c programming and i have the code for the programs that it wants at the bottom i jut dont know how to call the functions Program 2:Tip,Tax,Total int main(void) {    // Constant and Variable Declarations    double costTotal= 0;    double taxTotal = 0;    double totalBill = 0;    double tipPercent = 0;    // *** Your program goes here ***    printf("Enter amount of the bill: $");    scanf("%lf", &costTotal);    printf("\n");    // *** processing ***    taxTotal = 0.07 * costTotal;    totalBill...

  • PYTHON PROGRAMMING LANGUAGE (NEEDED ASAP) Using a structured approach to writing the program: This section will...

    PYTHON PROGRAMMING LANGUAGE (NEEDED ASAP) Using a structured approach to writing the program: This section will guide you in starting the program in a methodical way. The program will display a window with GUI widgets that are associated with particular functions: Employee Payroll O X -- - - - - - - - - - - Show Payroll Find Employee by Name Highest Lowest Find Employee by Amount Write Output to Fie Cancel - -------- ------------- Notice that some of...

  • Introduction In this final programming exercise, you'll get a chance to put together many of the...

    Introduction In this final programming exercise, you'll get a chance to put together many of the techniques used during this semester while incorporating OOP techniques to develop a simple song playlist class. This playlist class allows a user to add, remove and display songs in a playlist. The Base Class, Derived Class and Test Client Unlike the other PAs you completed in zyLabs, for this PA you will be creating THREE Java files in IntelliJ to submit. You will need...

  • In C++ Programming Write a program in Restaurant.cpp to help a local restaurant automate its breakfast...

    In C++ Programming Write a program in Restaurant.cpp to help a local restaurant automate its breakfast billing system. The program should do the following: Show the customer the different breakfast items offered by the restaurant. Allow the customer to select more than one item from the menu. Calculate and print the bill. Assume that the restaurant offers the following breakfast items (the price of each item is shown to the right of the item): Name Price Egg (cooked to order)...

  • Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons...

    Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons in the party through a text field. Calculate and display the amount owed by each person in the party if the bill is to be split evenly among the party members. /////////// TipCalculatorController.java: import java.math.BigDecimal; import java.math.RoundingMode; import java.text.NumberFormat; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.TextField; public class TipCalculatorController { // formatters for currency and percentages private...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT