class FirstViewModel(oldCounter: Int) : ViewModel() {
val counter: LiveData<Int>
get() = _counter
private var _counter = MutableLiveData<Int>()
init {
_counter.value = oldCounter
}
fun add() {
val count = _counter.value ?: 0
_counter.value = count + 1
}
fun clear() {
_counter.value = 0
}
}
Activity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
// ViewModel
viewModel = ViewModelProvider(this).get(FirstViewModel::class.java)
// UI
val startBtn: AppCompatButton = findViewById(R.id.first_start_btn)
contentTv = findViewById(R.id.first_content_tv)
startBtn.setOnClickListener {
viewModel.add()
}
viewModel.counter.observe(this) {
contentTv.text = it.toString()
}
}