How to create an Android Tip Calculator Application

In this tutorial we are going to learn how to create a simple android tip calculator app. If you don’t know what a tip calculator app is then lets explain it in a simple way.

A tip calculator is use to share tips given to a group of people working together. It is commonly seen in fast food and restaurant related businesses.

When a bill is given to a customers, a certain percentage of the bill is a tip. The tip can be deducted from the total amount and it will be shared in accordance with the rules guiding tip sharing in the business.

Enough of what tip calculator is. Lets focus now on how we will implement an android tip calculator in our project.

What we will do in this application is to create an EditText where users will enter the total amount of the bill to be paid.

The app will also has two Seekbar Views which will be used to control the percentage of tips and number of people that will share the tip.

The display section will contain three TextView controls

1. Total amount to be paid

2. Total amount of tip to be paid

3. Tip per person

Right now it is important for us to understand what we are planning to achieve in this tutorial. The screen-shot of our project is shown below.

tip calculator

Before we start, it is important for you to understand the tools and environment I used in this android tutorial. Feel free to use any tools you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidTipCalculator

Package: com.inducesmile.androidtipcalculator

Select Blank Activity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

If you are using Android Studio as your choice IDE, the new project will create a default

MainActivity.java file and its corresponding layout file.

The default layout file is the activity_main.xml. Open you layout file and add all the required View components that we need. The code sample for our layout file is as shown below.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/icons">
        <ScrollView
            android:id="@+id/scroll_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_above="@+id/calculate_tips"
            android:layout_marginBottom="6dp"
            android:background="#ffffff"
            android:padding="16dp"
            android:scrollbars="none">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <TextView
                    android:id="@+id/first_binary"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_marginTop="8dp"
                    android:text="@string/total_bill"
                    android:textStyle="bold"
                    android:textColor="@color/primary_text" />
                <EditText
                    android:id="@+id/bill_value"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/first_binary"
                    android:layout_marginTop="4dp"
                    android:lines="3"
                    android:inputType="numberDecimal"
                    android:background="@drawable/bottom_border"
                    android:padding="8dp" />
                <TextView
                android:id="@+id/tip_percent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="24dp"
                android:layout_below="@+id/bill_value"
                android:text="@string/tip_percent"
                android:textStyle="bold"
                android:textColor="@color/primary_text" />
                <SeekBar
                    android:id="@+id/seekBar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="4dp"
                    android:layout_below="@+id/tip_percent"/>
                <TextView
                    android:id="@+id/split_number"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="24dp"
                    android:layout_below="@+id/seekBar"
                    android:text="@string/split_number"
                    android:textStyle="bold"
                    android:textColor="@color/primary_text" />
                <SeekBar
                    android:id="@+id/seekBar_one"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="4dp"
                    android:max="10"
                    android:layout_below="@+id/split_number"/>
                <TextView
                    android:id="@+id/total_to_pay"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="24dp"
                    android:layout_below="@+id/seekBar_one"
                    android:text="@string/total_amount_to_pay"
                    android:textStyle="bold"
                    android:textColor="@color/primary_text" />
                <TextView
                    android:id="@+id/total_to_pay_result"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="4dp"
                    android:layout_below="@+id/total_to_pay"
                    android:textStyle="bold"
                    android:background="@drawable/bottom_border"
                    android:textColor="@color/primary_text" />
                <TextView
                    android:id="@+id/total_tip"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="24dp"
                    android:layout_below="@+id/total_to_pay_result"
                    android:text="@string/total_tip"
                    android:textStyle="bold"
                    android:textColor="@color/primary_text" />
                <TextView
                    android:id="@+id/total_tip_result"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="4dp"
                    android:layout_below="@+id/total_tip"
                    android:textStyle="bold"
                    android:background="@drawable/bottom_border"
                    android:textColor="@color/primary_text" />
                <TextView
                    android:id="@+id/tip_per_person"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="24dp"
                    android:layout_below="@+id/total_tip_result"
                    android:text="@string/tip_per_person"
                    android:textStyle="bold"
                    android:textColor="@color/primary_text" />
                <TextView
                    android:id="@+id/tip_per_person_result"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="4dp"
                    android:layout_below="@+id/tip_per_person"
                    android:textStyle="bold"
                    android:background="@drawable/bottom_border"
                    android:textColor="@color/primary_text" />
            </RelativeLayout>
        </ScrollView>
    <Button
        android:id="@+id/calculate_tips"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/calculate_tip"
        android:textAllCaps="false"
        android:background="@color/primary"
        android:padding="12dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="8dp"
        android:layout_alignParentBottom="true"/>
    </RelativeLayout>

The layout file is simple so it does not need much explanation but if you have any question, kindly use the comment box below to get in contact with me.

Now that we have done with our layout file, we will move over to our Activity file – MainActivity.java file.

Open your project MainActivity.java file, we will get the instances of all our controls that we need for calculation.

package com.inducesmile.completecalculatorapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private EditText totalBillAmount;
    private SeekBar tipPercent;
    private SeekBar tipsNumberOfPeople;
    private TextView totalAmountToBePaid;
    private TextView totalAmountOfTipsToBePaid;
    private TextView tipsPerPerson;
    private Button calculateTips;
    private int tipPercentValue = 0;
    private int tipsForNumberOfPeople = 0;
    private TextView tipPercentLabel;
    private TextView splitNumberLabel;
   

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_tip_calculator); 
    totalBillAmount = (EditText)findViewById(R.id.bill_value);
    tipPercent = (SeekBar)findViewById(R.id.seekBar);
    tipsNumberOfPeople = (SeekBar)findViewById(R.id.seekBar_one);

    totalAmountToBePaid = (TextView)findViewById(R.id.total_to_pay_result);
    totalAmountOfTipsToBePaid = (TextView)findViewById(R.id.total_tip_result);
    tipsPerPerson = (TextView)findViewById(R.id.tip_per_person_result);
    tipPercentLabel = (TextView)findViewById(R.id.tip_percent);
    splitNumberLabel = (TextView)findViewById(R.id.split_number);
    
tipPercent.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tipPercentValue = progress;
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                tipPercentLabel.setText("Tip Percent - " + seekBar.getProgress());
            }
        });
        tipsNumberOfPeople.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tipsForNumberOfPeople = progress;
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                splitNumberLabel.setText("Split Number - " + seekBar.getProgress());
            }
        });
        calculateTips = (Button) view.findViewById(R.id.calculate_tips);
        calculateTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (totalBillAmount.getText().toString().equals("") || totalBillAmount.getText().toString().isEmpty()) {
                    Toast.makeText(getActivity(), "All Input field must be filled", Toast.LENGTH_LONG).show();
                    return;
                }
                double totalBillInput = Double.parseDouble(totalBillAmount.getText().toString());
                if (tipPercentValue == 0 || tipsForNumberOfPeople == 0) {
                    Toast.makeText(getActivity(), "Set values for Tip percent and split number", Toast.LENGTH_LONG).show();
                    return;
                }
                double percentageOfTip = (totalBillInput * tipPercentValue) / 100;
                double totalAmountForTheBill = totalBillInput + percentageOfTip;
                double tipPerEachPerson = percentageOfTip / tipsForNumberOfPeople;
                totalAmountToBePaid.setText(removeTrailingZero(String.valueOf(String.format("%.2f", totalAmountForTheBill))));
                totalAmountOfTipsToBePaid.setText(removeTrailingZero(String.valueOf(String.format("%.2f", percentageOfTip))));
                tipsPerPerson.setText(removeTrailingZero(String.valueOf(String.format("%.2f", tipPerEachPerson))));
            }
        });
        return view;
    }
public String removeTrailingZero(String formattingInput) {
        if (!formattingInput.contains(".")) {
            return formattingInput;
        }
        int dotPosition = formattingInput.indexOf(".");
        String newValue = formattingInput.substring(dotPosition, formattingInput.length());
        if (newValue.startsWith(".0")) {
            return formattingInput.substring(0, dotPosition);
        }
        return formattingInput;
    }
}

From the code above, you can see that we used the Activity class method findViewById() to get the instances of our View components.

The Seekbar event handler – OnSeekBarChangeListener() was implemented in order for user of our tips calculator app to set the actual value they need.

The button object was wire with a click event. When the calculate button of the application is clicked, we will obtain all the user inputs and use them to do the tip calculation and display the final result.

There is also a method we created called the removeTrailingZero(String formattingInput) . It takes a string as a parameter. It will strip the string value from any tailing zeros at the end of the string value.

This brings us to the end of this tutorial, If you find anything confusing kindly contact me with your questions or use the comment box below.

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive our new post once it is published.

You can see a working version of the application in my application – Daily Pocket Calculator in Google Play Store.

Download it and let me know what you think about it.

One Response

Add a Comment