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

Application on Android Studio "Tip Calculator" that calculates tip amount and total bill amount 1. Takes...
Application on Android Studio "Tip Calculator" that calculates tip amount and total bill amount 1. Takes as input a bill amount. 2. Allows user to select a tip percentage between 0-25% 3. Displays tip amount and total amount (total amount = bill amount+ tip amount) Hint: As tip percentage is a fixed range, you can use a SEEKBAR and as user slides the bar, auto calculate the tip amount and total amount.
Tip Calculator Instructions For this project you are to create a tip calculator that will take...
Tip Calculator Instructions For this project you are to create a tip calculator that will take a decimal/or non decimal amount and calculate the different tip values of that amount: 10% 15% 20% And display them appropriately. The values will be set to two decimal places. If you have an empty value, then a message will display informing the user of such. When the device is rotated the error message or tip information must continue to be displayed. in Android/Java
C# Tip Calculator. I can't figure the code out for this assignment can I get some...
C# Tip Calculator. I can't figure the code out for this assignment can I get some help For this assignment, you'll create a simple tip calculator. Expected program flow: Ask the user for the bill total. Ask the user for the tip percent. Print the final output in the following format when the user enters 10 and 15 for the first two prompts: Total for bill $10.00 with a 15% tip is $11.50 Note that the money values should be...
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...
I need the java code for a 4-function calculator app on android studio (do this on...
I need the java code for a 4-function calculator app on android studio (do this on android studio). Please make sure all the requirements shown below are followed (such as the error portion and etc). The topic of this app is to simply create a 4 function calculator which calculates math expressions (add, subtract, multiply, and divide numbers). The requirements are the following : - The only buttons needed are 0-9, *, /, +, -, a clear, and enter button...
I need the java code for a 4 function calculator app on android studio (do this...
I need the java code for a 4 function calculator app on android studio (do this on android studio) - The requirements are the following : - The only buttons needed are 0-9, *, /, +, -, a clear, and enter button - Implement the onclicklistener on the main activity - The calcuator should use order of operations (PEMDAS) - It should be able to continue from a previous answer (Ex: If you type 2+6 the calculator will display 8....
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
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT