import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.Observer
class MainActivity : ComponentActivity() {
private val viewModel: CounterViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val countTextView = findViewById<TextView>(R.id.countTextView)
val incrementButton = findViewById<Button>(R.id.incrementButton)
viewModel.count.observe(this) { count ->
countTextView.text = "Count: $count"
}
incrementButton.setOnClickListener {
viewModel.incrementCount()
}
}
}
class CounterViewModel : ViewModel() {
private val _count = MutableLiveData(0)
val count: LiveData<Int> = _count
fun incrementCount() {
val current = _count.value ?: 0
_count.value = current + 1
}
}This app uses a ViewModel to hold the count number. The ViewModel stores the count in a MutableLiveData which allows the UI to observe changes and update automatically.
When the user taps the 'Increment Count' button, the ViewModel updates the count value. Because the ViewModel is tied to the activity lifecycle but survives configuration changes, the count value stays the same even if the screen rotates.
This means the UI will show the correct count after rotation without losing data or needing to save state manually.