Home Development for Android Creating a tip calculator in Kotlin: how does it work?

Creating a tip calculator in Kotlin: how does it work?

by admin

Creating a tip calculator in Kotlin: how does it work?
Here’s how to create a simple tip calculation app in Kotlin.More specifically, Kotlin 1.3.21, Android 4, Android Studio 3.This article will be interesting first of all for those who are starting their way in Android application development. It allows you to understand what and how works inside the application.
Such a calculator comes in handy when you need to calculate the amount of tips from the company who decided to spend time in a restaurant or cafe. Of course, not everyone and not always leave tips for waiters, it’s more of a Western tradition, but the process of developing such an application is interesting in any case.

Reminder : For all "Habr" readers – 10 000 rubles discount when you sign up for any Skillbox course with "Habr" promo code.
Skillbox recommends : Practical course "Mobile Developer PRO

This is what the application looks like while it is running :
Creating a tip calculator in Kotlin: how does it work?
You enter the desired percentage of the total amount, the number of participants in the meeting and get the result – the amount of tip to leave.

Beginning

The full application interface looks like this :
Creating a tip calculator in Kotlin: how does it work?
Creating a tip calculator in Kotlin: how does it work?
The first action is. loading the basis of the project Open it in Android Studio 3.0 or later. Build and run the project and see a white screen. That’s okay, that’s how it should be.
Creating a tip calculator in Kotlin: how does it work?
Creating a tip calculator in Kotlin: how does it work?
The user’s actions are written in chronological order in the project, so that everything is clear. To view it, open View -> Tool Windows -> TODO.
Examine the project and open colors.xml to evaluate the color palette. Strings.xml contains the text data (captions), and styles.xml has some font patterns.

Development of the cost section

Open activity_main.xml and add the code below to LinearLayout (#1):

<TextViewandroid:id="@+id/expensePerPersonTextView"android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingTop="30dp"style="@style/h1Bold"android:textColor="@color/colorAccent"android:text="0"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:paddingBottom="25dp"style="@style/h2"android:textColor="@color/colorAccent"android:text="@string/perPersonStaticText"/>

Now you can customize the style of the values directory or play with the colors using tool material.io
Now the project looks like this :
Creating a tip calculator in Kotlin: how does it work?
As you can see, the cost calculation is based on the data that the user contributes.

Accounts section development

We add the code below to the LinearLayout after the Expense Section (#2):

<LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="@color/colorAccent"><! — TODO #3: Build Bill Section →…</LinearLayout>

Close LinearLayout after the TODOs list, and then add new code, placing it inside LinearLayout (#3):

<TextViewandroid:layout_margin="15dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:textColor="@color/colorWhite"style="@style/h4"android:text="@string/billStaticText"/><EditTextandroid:id="@+id/billEditText"android:layout_width="match_parent"android:layout_height="wrap_content"android:textColor="@color/colorWhite"android:inputType="numberDecimal"android:maxLines="1"style="@style/h2Bold"android:text="0"/>

Since the main task of the application is to calculate individual costs for each of the participants in the restaurant, the costPerPersonTextView plays the main role.
EditText restricts data entry to a single line, this parameter must have a NumberDecimal inputType value.
Creating a tip calculator in Kotlin: how does it work?
Run the project for the test and enter the parameters of the total damage (broken cups, plates, etc.)

Development of the "People and Tip" section

To add a tip volume selection, paste the code below into a new LinearLayout section (#4):

<TextViewandroid:layout_margin="15dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:textColor="@color/colorWhite"style="@style/h4"android:text="@string/tipStaticText"/><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><ImageButtonandroid:id="@+id/subtractTipButton"style="@style/operationButton"android:layout_marginLeft="20dp"android:layout_marginStart="20dp"android:src="@drawable/subtract"/><TextViewandroid:id="@+id/tipTextView"android:layout_margin="15dp"android:layout_width="0dp"android:layout_height="wrap_content"android:textColor="@color/colorWhite"android:layout_weight="1"style="@style/h2Bold"android:text="20%"/><ImageButtonandroid:id="@+id/addTipButton"style="@style/operationButton"android:layout_marginEnd="20dp"android:layout_marginRight="20dp"android:src="@drawable/add"/></LinearLayout>

This section of the code is needed to accurately calculate the amount of the tip. The default value of the text is 20. ImageButtons are provided with icons in the folder with the write rights.
Copy the entire section and add the following (#5):

  • ImageButton ids (subtractPeopleButton, addPeopleButton)
  • TextView ids (numberOfPeopleStaticText, numberOfPeopleTextView)
  • DefaultText for numberOfPeopleTextView (must be 4).

Creating a tip calculator in Kotlin: how does it work?
Now when you start the app there is an option to add an invoice amount, the Add/Subtract buttons also work, but nothing is happening yet.

Add Views

Open MainActivity.kt and add this to the initViews function (#6):

private fun initViews() {expensePerPersonTextView = findViewById(R.id.expensePerPersonTextView)billEditText = findViewById(R.id.billEditText)addTipButton = findViewById(R.id.addTipButton)tipTextView = findViewById(R.id.tipTextView)subtractTipButton = findViewById(R.id.subtractTipButton)addPeopleButton = findViewById(R.id.addPeopleButton)numberOfPeopleTextView = findViewById(R.id.numberOfPeopleTextView)subtractPeopleButton = findViewById(R.id.subtractPeopleButton)//TODO #8: Bind Buttons to Listener//TODO #16: Bind EditText to TextWatcher}

Finishing buttons

To add support for click buttons, we implement View.OnClickListener at class level (#7):

class MainActivity : AppCompatActivity(), View.OnClickListener {

You can’t compile the project right now, you need to do some more steps (#8):

override fun onClick(v: View?) {when (v?.id) {R.id.addTipButton -> incrementTip()R.id.subtractTipButton -> decrementTip()R.id.addPeopleButton -> incrementPeople()R.id.subtractPeopleButton -> decrementPeople()}}

In terms of buttons and switches, Kotlin is organized in a very cool way! Let’s add the code below to all increment and decrement functions
(#9 -#12):

private fun incrementTip() {if (tipPercent != MAX_TIP) {tipPercent += TIP_INCREMENT_PERCENTtipTextView.text = String.format("%d%%", tipPercent)}}private fun decrementTip() {if (tipPercent != MIN_TIP) {tipPercent -= TIP_INCREMENT_PERCENTtipTextView.text = String.format("%d%%", tipPercent)}}private fun incrementPeople() {if (numberOfPeople != MAX_PEOPLE) {numberOfPeople += PEOPLE_INCREMENT_VALUEnumberOfPeopleTextView.text = numberOfPeople.toString()}}private fun decrementPeople() {if (numberOfPeople != MIN_PEOPLE) {numberOfPeople -= PEOPLE_INCREMENT_VALUEnumberOfPeopleTextView.text = numberOfPeople.toString()}}

Here the code protects the increment functions with maximum values (MAX_TIP MAX_PEOPLE). The code also protects the decrement functions with minimum values (MIN_TIP MIN_PEOPLE).
Now we associate buttons with listeners in the initViews function (#13):

private fun initViews() {...addTipButton.setOnClickListener(this)subtractTipButton.setOnClickListener(this)addPeopleButton.setOnClickListener(this)subtractPeopleButton.setOnClickListener(this)//TODO #15: Bind EditText to TextWatcher}

Creating a tip calculator in Kotlin: how does it work?
Now you can add the total damage, tips, and number of attendees to the meeting. And now the most important thing…

Costing section

This code counts costs (#14):

private fun calculateExpense() {val totalBill = billEditText.text.toString().toDouble()val totalExpense = ((HUNDRED_PERCENT + tipPercent) / HUNDRED_PERCENT) * totalBillval individualExpense = totalExpense / numberOfPeopleexpensePerPersonTextView.text = String.format("$%.2f", individualExpense)}

And here you call the function that allows you to count the number of people in the company and calculate the tips (#15):

private fun incrementTip() {…}private fun decrementTip() {…}private fun incrementPeople() {…}private fun decrementPeople() {…}

Let’s run the application. It looks and works great. But it could be better.
If you try to remove the account amount and then increase the number of tips or friends, the app will crash because there is not yet a check for a zero cost value. Moreover, if you try to change the invoice amount, the charges will not be updated.

Final Steps

Adding TextWatcher (#16):

class MainActivity : AppCompatActivity(), View.OnClickListener, TextWatcher {

Then we embed the billEditText listener (#17):

billEditText.addTextChangedListener(this)

Plus add code to run TextWatcher (#18):

override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {if (!billEditText.text.isEmpty()) {calculateExpense()}}override fun afterTextChanged(s: Editable?) {}override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

Creating a tip calculator in Kotlin: how does it work?
Well now absolutely everything works! Congratulations, you’ve written your own "Tip Calculator" in Kotlin.
Creating a tip calculator in Kotlin: how does it work?

Skillbox recommends :

You may also like