使用LiveData更新EditText需要遵循以下步骤:
示例代码:
使用观察LiveData对象的方式来更新EditText:
ViewModelProvider(this).get(MyViewModel::class.java).myLiveData.observe(this, Observer { editText.text = it })
在MyViewModel中定义LiveData:
class MyViewModel : ViewModel() {
val myLiveData = MutableLiveData()
}
将EditText与LiveData绑定:
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
viewModel.myLiveData.observe(this, Observer { editText.text = it })
使用监听LiveData对象的方式来更新EditText:
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
viewModel.myLiveData.observe(this, object : Observer {
override fun onChanged(it: String) {
editText.text = it
}
})