ViewModel & LiveData 介绍

1、介绍

通过实现一个猜词游戏介绍 ViewModel 和 LiveData
参考ViewModelLiveData原项目地址项目地址

2、代码设置

viewModel.currentScrambledWord.observe(viewLifecycleOwner) {
    binding.textViewUnscrambledWord.text = it
}

viewModel.currentWordCount.observe(viewLifecycleOwner){
    binding.wordCount.text = getString(R.string.word_count, it, MAX_NO_OF_WORDS)
}

viewModel.scope.observe(viewLifecycleOwner){
    binding.score.text = getString(R.string.score, it)
}

2、layout 设置

// Set the viewModel for data binding - this allows the bound layout access
// to all the data in the VieWModel
binding.viewModel = viewModel
binding.maxNoOfWords = MAX_NO_OF_WORDS

// Specify the fragment view as the lifecycle owner of the binding.
// This is used so that the binding can observe LiveData updates
binding.lifecycleOwner = viewLifecycleOwner
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容