1、介紹
通過實現(xiàn)一個猜詞游戲介紹 ViewModel 和 LiveData
參考ViewModel、LiveData、原項目地址、項目地址
2凭峡、代碼設(shè)置
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 設(shè)置
// 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