在 onViewCreated 与 onCreate 中获取 Fragment 中的 ViewModel

Get ViewModel in Fragment in onViewCreated vs in onCreate

我有一个 Android Activity 有一个 Fragment,我们把它命名为 MyFragment.

在 MyFragment 的 onCreate() 中,我的 ViewModel 是这样的:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    myViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class);
}

问题:

有时,当我将应用程序置于后台并导航到其他应用程序时,当我尝试打开此应用程序并将其返回到前台时,应用程序崩溃并出现以下错误:

Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.MyViewModel
    ...
    at com.example.MyFragment.onCreate(MyFragment.java:64)

第 64 行是这一行:

myViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class);

查看 ViewModel's official documentation 后,我注意到在代码片段中,在所有片段中,ViewModel 是在 onViewCreated() 中获取的,而不是 onCreate()。我将该更改应用于我的代码,并且我的应用程序不再因上述堆栈跟踪而崩溃。

问题:

  1. 为什么在 Fragment 的 onCreate() 中获取 ViewModel 会导致应用程序崩溃有任何特殊原因吗?如果是,那么为什么要获取 ViewModel onViewCreated() 似乎解决了这个问题?

  2. 我们是否应该始终在 onViewCreated() 中而不是在 onCreate() 中获取片段中的 ViewModel显示在官方文档的代码片段中?

这是由于 android 上存在的片段生命周期。你可以在这里阅读更多 https://developer.android.com/guide/fragments/lifecycle.

基本上,onCreate 仅在首次创建片段时调用。当您进入后台并再次恢复应用程序时,不会调用 onCreate() 函数并且调用 onCreateView() 或 onViewCreated() 。请参考下图。因此,当您在 OnCreate() 中初始化 viewModel 并将应用程序置于后台并将 return 放入应用程序时,因为没有调用 OnCreate(),不会创建 viewModel,因此它会崩溃。当在 OnViewCreated() 中时,viewModel 在应用程序 return 从后台开始时被初始化,因此没有崩溃。所以,是的,应该在 onViewCreate() 中初始化它。