How to use the Android ViewModel?

The Android ViewModel is a design pattern used to manage and retain data related to the UI. Its main purpose is to ensure data consistency during configuration changes, such as screen rotation, or when the application goes into the background and restarts.

To use Android ViewModel, you need to follow the following steps:

  1. Add ViewModel support library dependencies to your module-level build.gradle file.
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
  1. Create a class that inherits from ViewModel, which will store your UI-related data. For example:
import androidx.lifecycle.ViewModel

class MyViewModel : ViewModel() {
    // 保存您的 UI 相关数据的成员变量
}
  1. Retrieve an instance of ViewModel in your Activity or Fragment:
import androidx.lifecycle.ViewModelProvider

val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

Here, ‘this’ refers to your Activity or Fragment instance, and MyViewModel is the ViewModel class you have created.

  1. Now, you can utilize the data from ViewModel in your UI components. For example, in an Activity, you can set the text of a TextView like this:
textView.text = viewModel.myData

Here, myData is a member variable in MyViewModel.

  1. When your Activity or Fragment is destroyed, the ViewModel instance still exists, allowing data to be restored when it is recreated.

Please note that you can use LiveData in your ViewModel to observe and respond to changes in data. This way, your UI components can automatically update based on the data changes. For more information on LiveData, please refer to the LiveData documentation.

These are the basic steps for using Android ViewModel. You can further customize and extend the ViewModel according to your needs.

bannerAds