首页 > 解决方案 > 如果使用 Paging 3 库,onRestoreInstanceState 不适用于 RecyclerView 布局管理器

问题描述

我在保存 RecyclerView 状态时遇到问题,它通过保存布局管理器状态并在恢复片段后使用它来解决。(感谢@HarisDautović)

class TestFragment : Fragment() {

    private val testListAdapter: TestListAdapter by lazy {
        TestListAdapter()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_test, container, false)
    }

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


        postListView.apply {
            layoutManager = StaggeredGridLayoutManager(
                2, StaggeredGridLayoutManager.VERTICAL
            ).apply {
                gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS
            }
            setHasFixedSize(true)

            adapter = testListAdapter
        }
    }

    private var layoutManagerState: Parcelable? = null

    override fun onPause() {
        saveLayoutManagerState()
        super.onPause()
    }

    override fun onViewStateRestored(savedInstanceState: Bundle?) {
        super.onViewStateRestored(savedInstanceState)
        restoreLayoutManagerState()
    }

    private fun restoreLayoutManagerState () {
        layoutManagerState?.let { postListView.layoutManager?.onRestoreInstanceState(it) }
    }

    private fun saveLayoutManagerState () {
        layoutManagerState = postListView.layoutManager?.onSaveInstanceState()
    }

}

但如果使用分页 3 库它不起作用。只是导入这个库会导致问题,即使不在应用程序中使用它。

请查看此问题并接受答案的评论以获取更多详细信息: RecyclerView with StaggeredGridLayoutManager in ViewPager, 在返回片段时自动排列项目

标签: androidandroid-recyclerviewandroid-savedstateandroid-paging-libraryandroid-paging-3

解决方案


更新:

我的问题通过使用解决了:

testListAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT

和自定义恢复逻辑

旧答案: 问题来自 Recyclvew。使用有此问题的较新 alpha 版本的 recyclerView 的分页库。通过导入分页,整个项目使用这个版本的 recyclerview。强制使用稳定版 RecyclerView 解决问题。

在 build.gradle 中:

android {
    
    ...

    configurations.all {
        resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'androidx.recyclerview') {
                details.useVersion "1.1.0"
            }
        }
    }
}

推荐阅读