如果使用分页 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,arranges items automatically when going back to fragment

解决方法

更新:

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

testListAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT

和自定义恢复逻辑

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

在 build.gradle 中:

android {
    
    ...

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