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);
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Android——ViewModel需要有参构造报错
发表评论 取消回复