报错如下
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.xxx/com.xxx.xxx.MainActivity}
: java.lang.RuntimeException: Cannot create an instance of class com.xxx.xxx.viewmodel.MainActivityViewModel
Caused by: java.lang.RuntimeException:
Cannot create an instance of class com.xxx.xxx.viewmodel.MainActivityViewModel
最后解决:因为我的BaseViewModel是继承AndroidViewModel,需要Application类型的参数,所以图二中自己写的viewModel的入参类型必须是Application类型,不能写成自己继承实现的
//实例化方法
ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory(application))
.get(MainActivityViewModel::class.java)
最后我用的库版本如下:
api 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0'