0
0
Android Kotlinmobile~20 mins

ViewModel creation in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Counter Screen
A simple screen that shows a number and a button to increase it using ViewModel to keep the count.
Target UI
-------------------
|   Counter App   |
|                 |
|      0          |
|                 |
|  [Increase +]   |
-------------------
Create a ViewModel class to hold the counter value
Display the current count in the UI
Add a button that increases the count when clicked
Use ViewModel to keep the count even if the screen rotates
Starter Code
Android Kotlin
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModelProvider
import android.widget.Button
import android.widget.TextView

class MainActivity : ComponentActivity() {
    private val counterViewModel: CounterViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val countTextView = findViewById<TextView>(R.id.countTextView)
        val increaseButton = findViewById<Button>(R.id.increaseButton)

        // TODO: Observe the count LiveData from ViewModel and update countTextView

        // TODO: Set onClickListener on increaseButton to increase count in ViewModel
    }
}

// TODO: Create CounterViewModel class here
Task 1
Task 2
Task 3
Solution
Android Kotlin
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.LiveData
import android.widget.Button
import android.widget.TextView

class MainActivity : ComponentActivity() {
    private val counterViewModel: CounterViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val countTextView = findViewById<TextView>(R.id.countTextView)
        val increaseButton = findViewById<Button>(R.id.increaseButton)

        counterViewModel.count.observe(this) { count ->
            countTextView.text = count.toString()
        }

        increaseButton.setOnClickListener {
            counterViewModel.increaseCount()
        }
    }
}

class CounterViewModel : ViewModel() {
    private val _count = MutableLiveData(0)
    val count: LiveData<Int> = _count

    fun increaseCount() {
        _count.value = (_count.value ?: 0) + 1
    }
}

We created a CounterViewModel class that holds a MutableLiveData integer starting at 0. This LiveData keeps the count value.

In MainActivity, we get the ViewModel instance using by viewModels(). We observe the count LiveData and update the TextView whenever the count changes.

The button's click listener calls increaseCount() on the ViewModel, which increments the count. Because the count is in ViewModel, it survives screen rotations and keeps the number consistent.

Final Result
Completed Screen
-------------------
|   Counter App   |
|                 |
|      3          |
|                 |
|  [Increase +]   |
-------------------
When user taps 'Increase +' button, the number in the center increases by 1
The count stays the same if the device is rotated
Stretch Goal
Add a Reset button that sets the count back to zero
💡 Hint
Add another button in the layout and a resetCount() method in ViewModel to set _count.value = 0