📅  最后修改于: 2023-12-03 15:05:49.947000             🧑  作者: Mango
The ViewModelProviders.of(this)
method is used to retrieve a ViewModelProvider
for the given FragmentActivity
or Fragment
. This method is used to retrieve a ViewModel
instance for a given FragmentActivity
or Fragment
. By using ViewModelProviders.of(this).get(ViewModel.class)
, we retrieve a ViewModel
that is scoped to the FragmentActivity
or Fragment
. This means that the ViewModel
will be retained even when the FragmentActivity
or Fragment
is recreated.
In Android, when the Fragment
or Activity
is recreated on configuration changes, the data that was being displayed is lost. This is a big problem when you are dealing with a lot of data that needs to be displayed in the UI. With ViewModelProviders.of(this)
, we can solve this problem by retaining the data across configuration changes.
The ViewModel
class is designed to store and manage UI-related data in a lifecycle-conscious way. The ViewModel
class allows data to survive configuration changes such as screen rotations.
By using ViewModelProviders.of(this)
, we can ensure that the ViewModel
instance is retained across configuration changes, so the data will not be lost.
To use ViewModelProviders.of(this)
, you first need to add the ViewModel
dependency to your project. Here's how to add the ViewModel
dependency:
dependencies {
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
}
After adding the ViewModel
dependency, you can use ViewModelProviders.of(this)
to retrieve the ViewModel
instance. Here's an example:
public class MyFragment extends Fragment {
private MyViewModel viewModel;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
}
}
In this example, we retrieve the ViewModel
instance by passing the Fragment
instance to the ViewModelProviders.of(this)
method. We then call the get()
method, passing in the ViewModel
class as a parameter.
In this tutorial, we learned about the ViewModelProviders.of(this)
method, which is used to retrieve a ViewModelProvider
for the given FragmentActivity
or Fragment
. We also learned about the benefits of using the ViewModel
class in Android development, and how to use ViewModelProviders.of(this)
to retrieve a ViewModel
instance that will be retained across configuration changes.
By using ViewModelProviders.of(this)
, we can ensure that our ViewModel
instance is retained across configuration changes, so our data will not be lost. This makes our app more robust and user-friendly, and helps us create a better user experience.