首先,检查ViewModel是否正确地更新了LiveData数据。其次,确保UI正确地绑定了LiveData数据。最后,确保您的布局文件正确地包括绑定表达式和布局变量。以下是具体的代码示例:
ViewModel示例:
class MyViewModel : ViewModel() {
private val _text = MutableLiveData()
val text: LiveData
get() = _text
fun updateText(newText: String) {
_text.value = newText
}
}
MainActivity示例:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.lifecycleOwner = this
binding.viewModel = viewModel
viewModel.text.observe(this, Observer { newText ->
binding.textView.text = newText
})
binding.button.setOnClickListener {
viewModel.updateText("New text")
}
}
}
activity_main.xml示例: