Day79 of #100DaysOfCode
2 min readApr 26, 2022
Hii folks 🙌
Today I will be continuing the same pathway in which we will calculate the price from order details.
Unit 3: Navigation
Pathway 3: Advanced navigation app Examples
https://developer.android.com/courses/android-basics-kotlin/course
Calculate price from order details
Looking at the final app screenshots of this codelab, we’ll notice that the price is actually displayed on each fragment (except the StartFragment
) so the user knows the price as they create the order.
We will update the price in ViewModel.
package ...
import ...
private const val PRICE_PER_CUPCAKE = 2.00
class OrderViewModel : ViewModel() {
...
- Now that we have defined a price per cupcake, we will create a helper method to calculate the price. This method can be
private
because it's only used within this class.
private fun updatePrice() {
_price.value = (quantity.value ?: 0) * PRICE_PER_CUPCAKE
}
- For the
subtotal
text view, set the value of theandroid:text
attribute to be"@{@string/subtotal_price(viewModel.price)}".
...
<TextView
android:id="@+id/subtotal"
android:text="@{@string/subtotal_price(viewModel.price)}"
... />
...
- Then we will run the app and if we select One Cupcake in the fragment, it will show the Subtotal
12.0.
Now we will make a similar change for the pickup and summary fragments. Infragment_pickup.xml
andfragment_summary.xml
layouts, modify the text views to use theviewModel
price
property as well.
fragment_pickup.xml
...
<TextView
android:id="@+id/subtotal"
...
android:text="@{@string/subtotal_price(viewModel.price)}"
... />
...
fragment_summary.xml
<TextView
android:id="@+id/total"
...
android:text="@{@string/total_price(viewModel.price)}"
... />
That is all for Day79 ✅
Thanks for reading, See you tomorrow!