TestViewModel 继承ViewModel 此时需要传activity 到viewmodel 中 方法如下
有参的构造方法 获取TestViewModel
fun getTestViewModel(activity: BaseActivity): TestViewModel {
return ViewModelProviders.of(activity, object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(TestViewModel::class.java)) {
return TestViewModel(activity) as T
}
throw IllegalArgumentException(" unKnown ViewModel class ")
}
}).get(TestViewModel::class.java)
}
无参的构造方法 获取TestViewModel
viewModel = ViewModelProviders.of(this).get(TestViewModel ::class.java)