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.