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);
        }

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部