Day41 of #100DaysOfCode
Hii folks 🙌
Today I completed pathway 1 of Unit 2 of the Android Basic with Kotlin.
Unit 2: Layouts
Pathway 1: Get user input in an app — Part 1
Source: https://developer.android.com/courses/android-basics-kotlin/course
Today my task was to write down the function for my android app to calculate the tip, assessing all the UI components of the app.
So, the android provides a feature called view binding. With a little more work upfront, view binding makes it much easier and faster to call methods on the views in our UI.
So, in the build.gradle
file I enabled the viewBinding
feature.
buildFeatures {
viewBinding true
}
Then in the MainActivity.kt
initialized the binding object.
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
This line initializes the binding object.
binding = ActivityMainBinding.inflate(layoutInflater)
Now, I wrote the function calculateTip()
which will calculate the tip as per the user input.
fun calculateTip() {
val stringInTextField = binding.costOfService.text.toString()
val cost = stringInTextField.toDouble()
val selectedId = binding.tipOptions.checkedRadioButtonId
val tipPercentage = when (selectedId) {
R.id.option_twenty_percent -> 0.20
R.id.option_eighteen_percent -> 0.18
else -> 0.15
}
var tip = tipPercentage * cost
val roundUp = binding.roundUpSwitch.isChecked
if (roundUp) {
tip = kotlin.math.ceil(tip)
}
val formattedTip = NumberFormat.getCurrencyInstance().format(tip)
binding.tipResult.text = getString(R.string.tip_amount, formattedTip)
}
Now the app looks something like this which calculates the tip as per the user’s input. It was fun building one.
Today I Learned:
- View binding lets us more easily write code that interacts with the UI elements in our app
- Use the
checkedRadioButtonId
attribute of aRadioGroup
to find whichRadioButton
is selected. - Use
NumberFormat.getCurrencyInstance()
to get a formatter to use for formatting numbers as currency. - We can use string parameters like
%s
to create dynamic strings that can still be easily translated into other languages. - We can use Logcat in Android Studio to troubleshoot problems like the app crashing.
- Exceptions indicate a problem that the code didn’t expect.
- Not all code can handle
null
values, so be careful using it.
That is all for Day41 ✅
Thanks for reading, See you tomorrow!