如何证明 Android ViewModel

How to Prove Android ViewModel

我想问一些我认为可能有点基础的问题。当 Android 中有一些配置更改时,我如何证明 ViewModel class 不会被破坏?简而言之,如何证明下面的陈述,例如在 Android Studio 上的 logcat 中?

The ViewModel class is designed to store and manage UI-related data so that the data survives configuration changes such as screen rotations.

创建一个 viewmodel class 并声明它的一个变量,将一些数据放入其中并记录它或在 activity 的方向改变时烘烤 viewmodel 的数据:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

您还需要在清单中配置一些元素:

<activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">

数据将保留在视图模型中。如果没有,记录或烘烤时会有 nullpointexception

ViewModel 中有 onCleared 方法。您可以覆盖它。

ViewModel被销毁时,onCleared将被调用。

您会注意到,在使用 ViewModelMainActivityFragment 中旋转屏幕时,不会调用 onCleared 方法,即使 Activity.onDestroyed 确实如此。这是 ViewModel

的特点

onCleared 仅在 Activity 关闭时被调用 。使用 Activity.finish 或 backpress

之类的东西

我们有很多方法可以满足您的要求。

  • 您也可以使用 RxJava 2 来保存您的配置更改。
  • 您可以在清单中添加配置更改。
  • 您可以使用 onConfigurationChanged 覆盖方法。