本文介绍了从 AndroidViewModel 扩展时如何使用 ViewModelProvider.Factory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想向我的 ViewModel 发送一个额外的参数,但这从 AndroidViewModel 扩展而来.如何将此参数添加到 ViewModelFactory 类?
I want to send an extra parameter to my ViewModel, but this extends from AndroidViewModel.How can I add this parameter to the ViewModelFactory class ?
视图模型
class ProjectViewModel(application: Application) : AndroidViewModel(application) {
// need a param for project id...
}
视图模型工厂
class ProjectViewModelFactory(val projectId: Int): ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
// need to send this...
return ProjectViewModel(projectId) as T
}
}
注意:我注意到文档中说:AndroidViewModel 子类必须有一个接受应用程序作为唯一参数的构造函数.
Note: I notice that in the documentation its says: AndroidViewModel Subclasses must have a constructor which accepts Application as the only parameter.
所以我不知道做我想做的事情是否可行(或好).
So I don't know if it is posible (or good) to do what I'm trying to do.
推荐答案
获取 ViewModel:
Get ViewModel:
viewModel = ViewModelProviders.of(this,
new BListFactory(getActivity().getApplication(), 1))
.get(BListViewModel.class);
工厂:
class BListFactory extends ViewModelProvider.NewInstanceFactory {
@NonNull
private final Application application;
private final long id;
public BListFactory(@NonNull Application application, long id) {
this.application = application;
this.id = id;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (modelClass == BListViewModel.class) {
return (T) new BListViewModel(application, id);
}
return null;
}
}
AndroidViewModel:
AndroidViewModel:
public class BListViewModel extends AndroidViewModel {
private final long id;
public BListViewModel(@NonNull Application application, final long id) {
super(application);
this.id = id;
}
}
这篇关于从 AndroidViewModel 扩展时如何使用 ViewModelProvider.Factory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!