Process: com.wyg.util, PID: 32767
java.lang.RuntimeException: Cannot create an instance of class com.wyg.xc.XCViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory .create( ViewModelProvider.kt:204)
原因是自己ViewModel继承类的构造
public XCViewModel ( String name) {
this . name= name
}
解决方法
新建Factory类实现ViewModelProvider.Factory
public class XCViewModelFactory implements ViewModelProvider. Factory {
private String name;
public XCViewModelFactory ( String name) {
this . name = name;
}
@NonNull
@Override
public < T extends ViewModel > T create ( @NonNull Class < T > modelClass) {
if ( modelClass. isAssignableFrom ( XCViewModel . class ) ) {
return ( T ) new XCViewModel ( name) ;
}
throw new IllegalArgumentException ( "Unknown ViewModel class" ) ;
}
}
最后在Fragment继承类或Activity中使用
@Override
public void onViewCreated ( @NonNull View view, @Nullable Bundle savedInstanceState) {
String name= "张三" ;
XCViewModelFactory factory = new XCViewModelFactory ( name) ;
xcViewModel = new ViewModelProvider ( this , factory) . get ( XCViewModel . class ) ;
}