📜 ⬆️ ⬇️

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


We describe how to create a simple application for calculating tips in the Kotlin language. If more precisely, then Kotlin 1.3.21, Android 4, Android Studio 3. The article will be interesting, first of all, for those who begin their way in the development of Android applications. It allows you to understand what works inside the application and how.

This calculator is useful when you need to calculate the amount of tips from the company that decided to spend time in a restaurant or cafe. Of course, not everyone and not always leave the waiters for tea, this is more Western tradition, but the process of developing such an application is interesting in any case.

We remind: for all readers of "Habr" - a discount of 10,000 rubles when writing to any Skillbox course on the promotional code "Habr".

Skillbox recommends: Practical course “Mobile developer PRO .
Here is the application in the process of work:
')


You enter the desired percentage of the total amount, the number of participants in the meeting and get the result - the amount of tips that should be left.

Getting started


The full interface of the application is as follows:





The first step is to load the project base . Open it in Android Studio 3.0 or later. We build and run the project and see a white screen. Everything is normal, it should be so.





User actions are registered in the project in chronological order, so that everything is clear. To view it, open View -> Tool Windows -> TODO.

We study the project and open colors.xml to evaluate the color palette. Text data (captions) are placed in strings.xml, and there are several font templates in styles.xml.

Cost section development


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

<TextView android: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"/> <TextView android: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 values ​​directory style or play with colors using the material.io tool .

Now the project looks like this:


As you can see, the calculation of costs is made according to the data entered by the user.

Development of the accounts section


Add the code below in LinearLayout after Expense Section (# 2):

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

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

 <TextView android:layout_margin="15dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/colorWhite" style="@style/h4" android:text="@string/billStaticText"/> <EditText android: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 the calculation of individual costs for each of the participants of the gatherings in the restaurant, the main value is played by costPerPersonTextView.

EditText restricts data entry to a single line; this parameter must have the value NumberDecimal inputType.


We start the project for the test and we enter parameters of the general damage (the broken cups, plates, etc.)

Development of the section "People and Tips"


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

 <TextView android:layout_margin="15dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/colorWhite" style="@style/h4" android:text="@string/tipStaticText"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageButton android:id="@+id/subtractTipButton" style="@style/operationButton" android:layout_marginLeft="20dp" android:layout_marginStart="20dp" android:src="@drawable/subtract"/> <TextView android: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%"/> <ImageButton android:id="@+id/addTipButton" style="@style/operationButton" android:layout_marginEnd="20dp" android:layout_marginRight="20dp" android:src="@drawable/add"/> </LinearLayout> 

This piece of code is needed to accurately calculate the amount of tips. The default value of the text is 20. ImageButtons are equipped with icons in the folder with write permissions.

Fully copy the section and add the following (# 5):




Now, when launching the application, it is possible to add the invoice amount, the Add / Subtract buttons also work, but so far nothing has happened.

Adding 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 } 

Finish buttons


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

 class MainActivity : AppCompatActivity(), View.OnClickListener { 

Compile the project right now will not work, you need to perform a few more actions (# 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 at Kotlin, everything is organized very cool! Add the code below to all functions increment and decrement

(# 9 - # 12):

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

Here the code protects the function increments with maximum values ​​(MAX_TIP & MAX_PEOPLE). In addition, the code 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 } 



Now you can add total damage, tips and the number of participants in the meeting. Well, now the most important thing ...

Cost section


This code counts the costs (# 14):

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

Well, here a function is called that makes it possible to take into account the number of people in the company and calculate the tips (# 15):

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

Run the application. It looks and works great. But maybe better.

If you try to delete the invoice amount, and then increase the number of prompts or friends, the application will crash, because there is still no check for zero cost. Moreover, if you try to change the invoice amount, the expenses will not be updated.

Final steps


Add TextWatcher (# 16):

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

Then we build the billEditText listener (# 17):

 billEditText.addTextChangedListener(this) 

Plus, add the code to execute 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) {} 



Well, now it works absolutely everything! Congratulations, you wrote your own Tip Calculator on Kotlin.


Skillbox recommends:

Source: https://habr.com/ru/post/448582/


All Articles