Question

In: Computer Science

Murach Android tip calculator event handling assignment

Murach Android tip calculator event handling assignment

Solutions

Expert Solution

//MainActivity.java

package com.thephoenixzone.murachtipcalculator;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.text.NumberFormat;

public class MainActivity extends AppCompatActivity implements TextView.OnEditorActionListener, View.OnClickListener {

    // define variables for the widgets
    private EditText etbillAmount;
    private TextView txtPercent;
    private Button btnPercentUp;
    private Button   btnPercentDown;
    private TextView txtTip;
    private TextView txtTotal;

    // define the SharedPreferences object
    private SharedPreferences savedValues;

    // define instance variables that should be saved
    private String billAmount = "";
    private float tipPercent = .10f;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get references to the widgets
        etbillAmount = (EditText) findViewById(R.id.billAmountEditText);
        txtPercent = (TextView) findViewById(R.id.percentTextView);
        btnPercentUp = (Button) findViewById(R.id.percentUpButton);
        btnPercentDown = (Button) findViewById(R.id.percentDownButton);
        txtTip = (TextView) findViewById(R.id.tipTextView);
        txtTotal = (TextView) findViewById(R.id.totalTextView);

        // set the listeners
        etbillAmount.setOnEditorActionListener(this);
        btnPercentUp.setOnClickListener(this);
        btnPercentDown.setOnClickListener(this);

        // get SharedPreferences object
        savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
    }

    @Override
    public void onPause() {
        // save the instance variables
        SharedPreferences.Editor editor = savedValues.edit();
        editor.putString("billAmount", billAmount);
        editor.putFloat("tipPercent", tipPercent);
        editor.commit();

        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();

        // get the instance variables
        billAmount = savedValues.getString("billAmount", "");
        tipPercent = savedValues.getFloat("tipPercent", 0.15f);

        // set the bill amount on its widget
        etbillAmount.setText(billAmount);

        // calculate and display
        calculateAndDisplay();
    }

    public void calculateAndDisplay() {

        // get the bill amount
        billAmount = etbillAmount.getText().toString();
        float billAmount1;
        if (billAmount.equals("")) {
            billAmount1 = 0;
        }
        else {
            billAmount1 = Float.parseFloat(billAmount);
        }

        // calculate tip and total
        float tipAmount = billAmount1 * tipPercent;
        float totalAmount = billAmount1 + tipAmount;

        // display the other results with formatting
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        txtTip.setText(currency.format(tipAmount));
        txtTotal.setText(currency.format(totalAmount));

        NumberFormat percent = NumberFormat.getPercentInstance();
        txtPercent.setText(percent.format(tipPercent));
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE ||
                actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
            calculateAndDisplay();
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.percentDownButton:
                tipPercent = tipPercent - .01f;
                calculateAndDisplay();
                break;
            case R.id.percentUpButton:
                tipPercent = tipPercent + .01f;
                calculateAndDisplay();
                break;
        }
    }
}

//activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp" >

    <!-- The bill amount -->

    <TextView
        android:id="@+id/billAmountLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/bill_amount_label"
        android:textSize="20sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/billAmountEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/billAmountLabel"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/billAmountLabel"
        android:ems="8"
        android:inputType="numberDecimal"
        android:text="@string/bill_amount"
        android:textSize="20sp" >

        <requestFocus />
    </EditText>

    <!-- The tip percent -->

    <TextView
        android:id="@+id/percentLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/billAmountLabel"
        android:layout_below="@+id/billAmountLabel"
        android:padding="10dp"
        android:text="@string/tip_percent_label"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/percentTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/percentLabel"
        android:layout_alignLeft="@+id/billAmountEditText"
        android:padding="5dp"
        android:text="@string/tip_percent"
        android:textSize="20sp" />

    <Button
        android:id="@+id/percentDownButton"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_alignBaseline="@+id/percentTextView"
        android:layout_marginLeft="25dp"
        android:layout_toRightOf="@+id/percentTextView"
        android:text="@string/decrease"
        android:textSize="20sp" />

    <Button
        android:id="@+id/percentUpButton"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_alignBaseline="@+id/percentDownButton"
        android:layout_toRightOf="@+id/percentDownButton"
        android:text="@string/increase"
        android:textSize="20sp" />

    <!-- the tip amount -->

    <TextView
        android:id="@+id/tipLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/percentLabel"
        android:layout_below="@+id/percentLabel"
        android:padding="10dp"
        android:text="@string/tip_amount_label"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tipTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tipLabel"
        android:layout_alignLeft="@id/billAmountEditText"
        android:padding="5dp"
        android:text="@string/tip_amount"
        android:textSize="20sp" />

    <!-- the total -->

    <TextView
        android:id="@+id/totalLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tipLabel"
        android:layout_below="@+id/tipLabel"
        android:padding="10dp"
        android:text="@string/total_amount_label"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/totalTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/totalLabel"
        android:layout_alignLeft="@+id/tipTextView"
        android:padding="5dp"
        android:text="@string/total_amount"
        android:textSize="20sp" />

</RelativeLayout>

//strings.xml

<resources>
    <string name="app_name">MurachTipCalculator</string>
    <string name="title_activity_tip_calculator">Tip Calculator</string>
    <string name="menu_settings">Settings</string>

    <string name="bill_amount_label">Bill Amount</string>
    <string name="bill_amount"></string>

    <string name="tip_percent_label">Percent</string>
    <string name="tip_percent">15%</string>
    <string name="increase">+</string>
    <string name="decrease">-</string>

    <string name="tip_amount_label">Tip</string>
    <string name="tip_amount">$0.00</string>

    <string name="total_amount_label">Total</string>
    <string name="total_amount">$0.00</string>
</resources>

//Output


Related Solutions

05 Prepare : Checkpoint A Objective This assignment will give you practice writing event handling methods...
05 Prepare : Checkpoint A Objective This assignment will give you practice writing event handling methods to advance a ship in two dimensional space. Overview After completing (or while completing) the preparation material for this week, complete the following exercise. For this exercise, you will create a class that models a ship flying around in a 2-D plain (containing an x and y coordinate). A game class is provided to you that will help you call methods to advance and...
Modify the Tip Calculator app to allow the user to enter the number of people in...
Modify the Tip Calculator app to allow the user to enter the number of people in the party. Calculate and display the amount owed by each person if the bill were to be split evenly among the party members. Code: ----------------TipCalculator.java----------------------- import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class TipCalculator extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("TipCalculator.fxml")); Scene scene = new Scene(root); // attach scene graph to scene...
How can I configure the button in this tip calculator to calculate the total using the...
How can I configure the button in this tip calculator to calculate the total using the entires for the bill and tip percentage? I'm using Visual Studio 2019 Xamarin.Forms Main.Page.xaml <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="Accomplish_2.MainPage" BackgroundColor="Gray" Padding="5"> <StackLayout> <!-- Place new controls here --> <Label Text="Tip Calculator" HorizontalOptions="Center" VerticalOptions="Center" FontSize="Title" FontAttributes="Bold"/> <BoxView BackgroundColor="LightPink" HeightRequest="3"></BoxView>    <Entry Placeholder="Bill Total" Keyboard="Numeric" x:Name="billTotal"></Entry>    <Entry Placeholder="Tip Percentage" Keyboard="Numeric" x:Name="tipPercent"></Entry> <Button Text="Calculate" Clicked="Button_Clicked"></Button>    </StackLayout> </ContentPage> Everything above...
IN ANDROID STUDIO, you will create a mortgage calculator appthat allows the user to enter...
IN ANDROID STUDIO, you will create a mortgage calculator app that allows the user to enter a purchase price, down-payment amount, and an interest rate.Based on these values, the app should calculate the loan amount (purchase price minus down payment) and display the monthly payment for 10, 20, and 30-year loans.Allow the user to select a custom loan duration (in years) by using a SeekBar and display the monthly payment for that custom loan duration.Assignment deliverables (all in a ZIP...
Javascript Calculator Algorithm to calculate a tip percentage given the bill amount and total bill including...
Javascript Calculator Algorithm to calculate a tip percentage given the bill amount and total bill including tip. Asker suer for bill without tip: Ask the user for total bill with tip: Ask the user how many people splitting bill: Submit button to calculate the tip percentage
I am doing a 4 function calculator app in java on android studio which calculates math...
I am doing a 4 function calculator app in java on android studio which calculates math expressions (add, subtract, multiply, and divide). I ONLY NEED THE CODE THE EQUAL BUTTON. When the user clicks the equal button, it should take the entire sequence of numbers and operators on the screen, such as 1+2*5 , and save them into a String [I am pretty sure this can be done using the toString() call]. Then, the String should be split using StringTokenizer,...
In Python This assignment involves the use of text files, lists, and exception handling and is...
In Python This assignment involves the use of text files, lists, and exception handling and is a continuation of the baby file assignment. You should now have two files … one called boynames2014.txt and one called girlnames2014.txt - each containing the top 100 names for each gender from 2014. Write a program which allows the user to search your files for a boy or girl name and display where that name ranked in 2014. For example … >>>   Enter gender...
This assignment involves the use of text files, lists, and exception handling and is a continuation...
This assignment involves the use of text files, lists, and exception handling and is a continuation of the baby file assignment. You should now have two files … one called boynames2014.txt and one called girlnames2014.txt - each containing the top 100 names for each gender from 2014. Write a program which allows the user to search your files for a boy or girl name and display where that name ranked in 2014. For example … >>> Enter gender (boy/girl): boy...
For this activity, your assignment is to develop and complete a guide to materials handling hazards...
For this activity, your assignment is to develop and complete a guide to materials handling hazards and controls. You will need to develop a document that includes the following sections: General Materials Handling Manual Materials Handling Jacks Hand-Operated Materials Handling Vehicles Powered Vehicles and Forklifts Hoisting Apparatus Ropes, Chains, and Slings Conveyors Elevators, Escalators and Manlifts Bulk Materials, Excavation and Trenching Storage of Materials For each section, you should make a list of hazards and controls. You can make a...
This is a statistics calculator and simulator (Links to an external site.). For this assignment, I...
This is a statistics calculator and simulator (Links to an external site.). For this assignment, I would like you to start with a real life scenario in which you might need to know some statistical measures. Provide a real life scenario (you must have 10 numbers with a frequency of 1 and calculate the statistics) Take a screenshot of the completed stats. Now, change your frequencies to anything you want and see how the data changes. Take a screen shot...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT