我有以下课程:
public class MovieViewModel extends ViewModel {
private String query;
public MovieViewModel() {
MyFactory factory = new MyFactory(); //Pass the query in the constructor
//other stuff
}
}
在我的
MainActivity
中,我正在创建此类的对象,如下所示:MovieViewModel model = ViewModelProviders.of(this).get(MovieViewModel.class);
如何创建
MovieViewModel
类的对象,并同时初始化query
字符串,以便可以将其传递给MyFactory
构造函数? 最佳答案
您可以创建自定义工厂。
public class MovieViewModelFactory implements ViewModelProvider.Factory {
private Application mApplication;
private String mParam;
public MovieViewModelFactory(Application application, String param) {
mApplication = application;
mParam = param;
}
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new MovieViewModel(mApplication, mParam);
}
}
现在您可以像这样使用
MovieViewModel movieViewModel = ViewModelProviders.of(this, new MovieViewModelFactory(this.getApplication(), "param")).get(MovieViewModel.class);