问题描述
有没有办法将附加参数传递给我的自定义 AndroidViewModel
构造函数,除了应用程序上下文.示例:
Is there a way to pass additional argument to my custom AndroidViewModel
constructor except Application context.Example:
public class MyViewModel extends AndroidViewModel {
private final LiveData<List<MyObject>> myObjectList;
private AppDatabase appDatabase;
public MyViewModel(Application application, String param) {
super(application);
appDatabase = AppDatabase.getDatabase(this.getApplication());
myObjectList = appDatabase.myOjectModel().getMyObjectByParam(param);
}
}
当我想使用我的自定义 ViewModel
类时,我会在片段中使用此代码:
And when I want to user my custom ViewModel
class I use this code in my fragment:
MyViewModel myViewModel = ViewModelProvider.of(this).get(MyViewModel.class)
所以我不知道如何将附加参数 String param
传递到我的自定义 ViewModel
中.我只能传递应用程序上下文,而不能传递附加参数.我真的很感激任何帮助.谢谢你.
So I don't know how to pass additional argument String param
into my custom ViewModel
. I can only pass Application context, but not additional arguments. I would really appreciate any help. Thank you.
我添加了一些代码.我希望现在好点了.
I've added some code. I hope it's better now.
推荐答案
你的 ViewModel 需要有一个工厂类.
You need to have a factory class for your ViewModel.
public class MyViewModelFactory implements ViewModelProvider.Factory {
private Application mApplication;
private String mParam;
public MyViewModelFactory(Application application, String param) {
mApplication = application;
mParam = param;
}
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new MyViewModel(mApplication, mParam);
}
}
在实例化视图模型时,您可以这样做:
And when instantiating the view model, you do like this:
MyViewModel myViewModel = ViewModelProvider(this, new MyViewModelFactory(this.getApplication(), "my awesome param")).get(MyViewModel.class);
对于 kotlin,您可以使用委托属性:
For kotlin, you may use delegated property:
val viewModel: MyViewModel by viewModels { MyViewModelFactory(getApplication(), "my awesome param") }
还有另一个新选项 - 实现 HasDefaultViewModelProviderFactory
并使用工厂的实例化覆盖 getDefaultViewModelProviderFactory()
,然后调用 ViewModelProvider(this)
或 by viewModels()
没有工厂.
There's also another new option - to implement HasDefaultViewModelProviderFactory
and override getDefaultViewModelProviderFactory()
with the instantiation of your factory and then you would call ViewModelProvider(this)
or by viewModels()
without the factory.
这篇关于Android ViewModel 附加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!