有没有办法将附加参数传递给我的自定义 AndroidViewModel
除了应用程序上下文的构造函数。例子:
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
类时,我在我的片段中使用此代码:
MyViewModel myViewModel = ViewModelProvider.of(this).get(MyViewModel.class)
所以我不知道如何将附加参数 String param
传递给我的自定义 ViewModel
。我只能传递应用程序上下文,但不能传递其他参数。我真的很感激任何帮助。谢谢你。
编辑:我添加了一些代码。我希望现在好多了。
原文由 Mario Rudman 发布,翻译遵循 CC BY-SA 4.0 许可协议
您需要为您的 ViewModel 提供一个工厂类。
在实例化视图模型时,您可以这样做:
对于 kotlin,您可以使用委托属性:
There’s also another new option - to implement
HasDefaultViewModelProviderFactory
and overridegetDefaultViewModelProviderFactory()
with the instantiation of your factory and then you would callViewModelProvider(this)
orby viewModels()
没有工厂。