【问题标题】:How do I restore the previous RecyclerView state when a fragment is recreated?重新创建片段时如何恢复以前的 RecyclerView 状态?
【发布时间】:2021-08-08 04:09:07
【问题描述】:

我的 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 的数据?

【问题讨论】:

  • onSaveInstanceState 用于在配置发生变化时保存数据,例如旋转设备。当您关闭应用程序并再次启动它时,此数据将丢失。您可能需要使用其他方法来保存数据,例如 SharedPreferencesDataBase 以实现您的目标。

标签: android kotlin android-fragments android-recyclerview


【解决方案1】:

Farid 在评论中正确地说:这些方法用于 Activity 被销毁的情况,例如,内存不足或配置更改(屏幕旋转等)时。如果您只是单击了返回按钮,从而自己显式关闭了 Activity,那么这些方法将不会被执行。

如果您想在关闭应用程序后有数据,那么您必须将这些数据保存到持久内存中。 Preference Library 适用于存储最简单的变量。 如果数据结构比较复杂,最好使用Database

【讨论】:

  • 对于每个 RecyclerView 项目,我有它存储三个字符串值和一个 BigDecimal 值。需要数据库吗?我还应该提到每个用户的数据会有所不同,因为您必须先登录应用程序才能使用片段。
  • @TomDarious 如果你真的想缓存列表数据,那么你不能没有数据库。您将在第一次检索项目时保存此数据,因此每个人都有不同的数据不会有问题。
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 2013-08-27
  • 1970-01-01
  • 2019-10-06
相关资源
最近更新 更多