问题描述
是否有一种方法可以将其他参数传递给我的自定义AndroidViewModel
构造函数,除了Application上下文.示例:
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附加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!