如果使用 Paging 3 库,onRestoreInstanceState 不适用于 RecyclerView 布局管理器

onRestoreInstanceState not working for RecyclerView layout manager if using Paging 3 library

我在保存 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 库,则它不起作用。仅导入此库会导致问题,即使不在应用程序中使用它也是如此。

请查看此问题并接受答案的评论以了解更多详细信息:

更新:

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

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"
            }
        }
    }
}