我正在用Room
实现ViewModel
数据库。一切正常。但是要求是我想使用ViewModel
提供对AndroidViewModelFactory
的依赖。我可以创建实现ViewModelFactory
的ViewModelProvider.Factory
类。我传递一个普通的String作为对ViewModel的依赖。工厂类的代码是
public class TestViewModelFactory implements ViewModelProvider.Factory{
private static final String DEFAULT_LIMIT = "4";
static Application application;
static String created="ViewModelFactorySuccess";
public static TestViewModelFactory createFactory(Activity activity) {
application = activity.getApplication();
if (application == null) {
throw new IllegalStateException("Not yet attached to Application");
}
return new TestViewModelFactory(application, created);
}
public TestViewModelFactory(Application application, String created) {
application=application;
created=created;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
try {
return modelClass.getConstructor(TestViewModel.class, int.class)
.newInstance(application, created);
} catch (NoSuchMethodException | IllegalAccessException |
InstantiationException | InvocationTargetException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
}
}
}
在MainActivity
中,ViewModel
的普通实例创建为
TestViewModel testViewModel=new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(TestViewModel.class);
工作正常。但是如何创建ViewModel工厂类的实例,以便可以为ViewModel提供依赖项。请为ViewModel
实例创建建议正确的方法。任何帮助,将不胜感激。
一般示例,
MyViewModel myViewModel = ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication(), "Your string parameter")).get(MyViewModel.class);
就您而言,
TestViewModel testViewModel = ViewModelProviders.of(this, new TestViewModelFactory(this.getApplication(),"Your String Parameter").get(TestViewModel.class)