重新创建片段时如何恢复以前的 RecyclerView 状态?

How do I restore the previous RecyclerView state when a fragment is recreated?

我的 Android 应用程序中有一个 Fragment,它有一个 RecyclerView,我想恢复用户上次打开之前的 RecyclerView应用程序。

在我的 Fragment 中,我有以下代码块用于保存和恢复 RecyclerView

private val LIST_STATE_KEY = "recycler_state"
private var recyclerViewState : Parcelable? = null
private lateinit var recyclerView: RecyclerView

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putParcelable(LIST_STATE_KEY, recyclerView.layoutManager?.onSaveInstanceState())
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = rootView.findViewById(R.id.recycler_view)

    if (savedInstanceState != null) {
        recyclerViewState = savedInstanceState?.getParcelable(LIST_STATE_KEY)
    }
}

override fun onResume() {
    super.onResume()
    if (recyclerViewState != null) {
        recyclerView.layoutManager?.onRestoreInstanceState(recyclerViewState)
        recyclerView.adapter?.notifyDataSetChanged()
    }
}

我现在遇到的问题是,当我第一次打开该应用程序时,我填充了 RecyclerView,关闭该应用程序,再次打开它,当我转到该特定片段时,RecyclerView 为空。我在这里做错了什么?为什么我的应用程序不保存它在应用程序关闭之前拥有的 RecyclerView 数据,并在应用程序再次打开时恢复它保存到 RecyclerView 的数据?

Farid 在评论中正确地说:这些方法在 Activity 被破坏的情况下使用,例如,当内存不足或配置更改时(屏幕旋转等) .如果您只是单击“后退”按钮,从而明确地自己关闭了 Activity,那么这些方法将不会被执行。

如果你想在关闭应用后有数据,那么你必须把这个数据保存到持久内存中。 Preference Library适合存放最简单的变量。 如果数据结构比较复杂,那么最好用Database.