43.6 Assigning the ViewModel Instance to the Data Binding Variable
At this point, the data binding knows that it will be binding to an instance of a class of type MainViewModel but has not yet been connected to an actual MainViewModel object. This requires the additional step of assigning the MainViewModel instance used within the app to the viewModel variable declared in the layout file. Since the reference to the ViewModel is obtained in the onActivityCreated() method, it makes sense to make the assignment there:
.
.
import com.ebookfrenzy.viewmodeldemo.BR.myViewModel
.
.
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
binding.setVariable(myViewModel, viewModel)
}
.
.
If Android Studio reports myViewModel as undefined, rebuild the project...