Calculate the tip

Last Updated on December 25, 2020 by AbdurRahman G Official | Md Ghufran Salafi

Calculate the tip:

 

Solution code

The solution code for this codelab is below.

966018df4a149822.png

MainActivity.kt

(note on the first line: replace the package name if yours is different than com.example.tiptime)

package com.example.tiptime

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.tiptime.databinding.ActivityMainBinding
import java.text.NumberFormat

class MainActivity : AppCompatActivity() {

   private lateinit var binding: ActivityMainBinding

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)

       binding = ActivityMainBinding.inflate(layoutInflater)
       setContentView(binding.root)

       binding.calculateButton.setOnClickListener { calculateTip() }
   }

   private fun calculateTip() {
       val stringInTextField = binding.costOfService.text.toString()
       val cost = stringInTextField.toDoubleOrNull()
       if (cost == null) {
           binding.tipResult.text = ""
           return
       }

       val tipPercentage = when (binding.tipOptions.checkedRadioButtonId) {
           R.id.option_twenty_percent -> 0.20
           R.id.option_eighteen_percent -> 0.18
           else -> 0.15
       }

       var tip = tipPercentage * cost
       if (binding.roundUpSwitch.isChecked) {
           tip = kotlin.math.ceil(tip)
       }

       val formattedTip = NumberFormat.getCurrencyInstance().format(tip)
       binding.tipResult.text = getString(R.string.tip_amount, formattedTip)
   }
}

Modify strings.xml

<string name="tip_amount">Tip Amount: %s</string>

Modify activity_main.xml

...

<TextView
   android:id="@+id/tip_result"
   ...
   tools:text="Tip Amount: $10" />

...

Modify the app module’s build.gradle

android {
    ...

    buildFeatures {
        viewBinding = true
    }
    ...
}

 

Summary

  • View binding lets you more easily write code that interacts with the UI elements in your app
  • The Double data type in Kotlin can store a decimal number
  • Use the checkRadioButtonId attribute of a RadioGroup to find which RadioButton is selected
  • Use NumberFormat.getCurrencyInstance() to get a formatter to use for formatting numbers as currency
  • You can use string parameters like %s to create dynamic strings that can still be easily translated into other languages
  • Testing is important!
  • You can use Logcat in Android Studio to troubleshoot problems like the app crashing
  • A stack trace shows a list of methods that were called. This can be useful if the code generates an exception.
  • Exceptions indicate a problem that code didn’t expect
  • Null means “no value”
  • Not all code can handle null values, so be careful using it
  • Use Analyze > Inspect Code for suggestions to improve your code

 

More Codelabs to improve your UI

Great job on getting the tip calculator to work! You’ll notice that there are still ways to improve the UI to make the app look more polished. If you’re interested, check out these additional codelabs to learn more about how to change the app theme and app icon, as well as how to follow best practices from the Material Design guidelines for the Tip Time app!

 

Learn more

 

Practice on your own

  • With the unit converter app for cooking in the previous practice, add code for the logic and calculations to convert units like milliliters to or from fluid ounces.

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *