package com.example.mvvmcounter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import com.example.mvvmcounter.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: CounterViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
viewModel.counter.observe(this, Observer { count ->
binding.textViewCounter.text = count.toString()
})
binding.buttonIncrease.setOnClickListener {
viewModel.increaseCounter()
}
}
}
class CounterViewModel : ViewModel() {
private val _counter = MutableLiveData(0)
val counter: LiveData<Int> = _counter
fun increaseCounter() {
_counter.value = (_counter.value ?: 0) + 1
}
}This solution uses the MVVM pattern by separating UI logic and data logic.
The CounterViewModel holds the counter data as LiveData. It starts at 0 and has a method to increase the count.
The MainActivity observes the LiveData from the ViewModel. When the counter changes, the UI text updates automatically.
The button click calls the ViewModel's increase method, keeping UI and data separate and reactive.