我知道为了将自定义参数传递给ViewModel,我们可以使用ViewModelProvider.NewInstanceFactory,像这样:
// Factory Class
class MyFactory extends ViewModelProvider.NewInstanceFactory {
private final String mId;
public MyFactory(String id) {
mId = id;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new MyViewModel(mId);
}
}
// MyViewModel class
class MyViewModel extends ViewModel {
public MyViewModel(String id) {
...
}
}
// Activity I can Initialise as:
MyFactory modelFactory = new MyFactory(id);
viewModel = ViewModelProviders.of(this, modelFactory).get(MyViewModel.class);
如何使用AndroidViewModel子类中的自定义参数以及应用程序上下文实现相同的效果。喜欢
// MyAndroidViewModel class
class MyAndroidViewModel extends AndroidViewModel {
public MyViewModel(Application context, String id) {
super(context);
...
}
}
如何初始化MyAndroidViewModel以及ViewModelProvider.NewInstanceFactory如何在这里发挥作用?
侃侃无极
相关分类