【问题标题】:how and where to save state of recycler view in fragment [duplicate]如何以及在哪里保存片段中回收器视图的状态[重复]
【发布时间】:2020-06-09 17:34:37
【问题描述】:

问题是我不知道如何保存内部片段中的回收器视图的状态。 当我进行新活动并返回上一个活动时,回收站视图从顶部开始,而不是我停止滚动的位置 当在互联网上搜索时,他们建议实施保存实例覆盖方法,但我不知道将该方法放在哪里意味着在片段或主要活动中以及如何在 onactivitycreated 方法中使用,以便当我回来时回收器视图确实不要上顶。

【问题讨论】:

  • 更具体地说,请参阅this answer 上的更新。
  • 但是在主要活动或片段类中的哪里添加方法??
  • 另一个问题的答案告诉你

标签: android android-studio android-fragments android-recyclerview


【解决方案1】:

如果您在片段之间导航并且想要保存视图状态,请将状态保存在onPause()onSaveInstanceState()

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
  //your code

}

把这个放到fragment类(onViewCreated())或者ActivityonCreate()

    var scrolled: Int = 0
        recyclerView!!.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                scrolled += dy //this one ro scroll vertically, if you want to horizontal scroll - change `dy` to `dx`

                val preferences = PreferenceManager.getDefaultSharedPreferences(context)
                preferences.edit()
                    .putInt("position", scrolled)
                    .apply()
            }
        })

并使用这个onResume()

 override fun onResume() {
    super.onResume()
    val preferences = PreferenceManager.getDefaultSharedPreferences(context)

    val index = preferences.getInt("position", 0)

    Handler().postDelayed({
        recyclerView!!.smoothScrollBy(0, index) //this one ro scroll vertically, if you want to horizontal scroll - `(index,0)`
    }, 50)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    相关资源
    最近更新 更多