问题
I am trying to initialize my viewmodel object in the FirstFragment.java
file of BasicActivity
. All theses four codes are failed. The documentation could not help me much.
mViewModel = new ViewModelProvider(this).get(MyViewModel.class);
mViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class);
mViewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class);
mViewModel = new ViewModelProvider(FirstFragment.class).get(MyViewModel.class);
On the other hand, public ViewModelProvider(@NonNull ViewModelStoreOwner owner)
ViewModelProvider is taking ViewModelStoreOwner as its parameter and in the FragmentActivity.java
ViewModelStore getViewModelStore()
method of ViewModelStore
interface is implemented may be in a factory pattern.
@NonNull
@Override
public ViewModelStore getViewModelStore() {
return FragmentActivity.this.getViewModelStore();
}
Help me initializing ViewModel
回答1:
Initializing your viewModel goes like:
if you are using
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
and Intialize your viewModel
viewModel = ViewModelProviders.of(this,viewModelFactory).get(MyViewModel.class);
but it's deprecated now. So update the dependency to:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
and initial your viewModel as follow:
viewModel = new ViewModelProvider(this,viewModelFactory).get(MyViewModel.class);
viewModelFactory is optional.
来源:https://stackoverflow.com/questions/61395560/initializing-viewmodel-in-fragment-android-java