我在保存RecyclerView状态时遇到问题,它通过保存布局管理器状态并在恢复片段后使用它来解决.(感谢@HarisDautović)
I had a problem in saving RecyclerView state and it solved by saving layout manager state and using it after resume fragment.(thanks to @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库,则它不起作用.只是导入此库会导致问题,即使不在应用程序中使用它也是如此.
but if using paging 3 library it does not work. just importing this library causes problem even not using it in app.
请查看此问题和接受的答案的评论以获取更多详细信息:在ViewPager中带有StaggeredGridLayoutManager的RecyclerView,当返回片段时会自动排列项目
please see this question and accepted answer's comments for more details: RecyclerView with StaggeredGridLayoutManager in ViewPager, arranges items automatically when going back to fragment
推荐答案更新:
我的问题通过使用解决:
my problem solved by using:
testListAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT和自定义恢复逻辑
旧答案:问题出在Recyclervew.使用较新的alpha版本的recyclerView的分页库存在此问题.通过导入分页,整个项目都使用此版本的recyclerview.强制使用稳定版的RecyclerView解决了该问题.
OLD ANSWER: problem is from Recyclervew. the paging library using a newer alpha version of recyclerView that have this problem. by importing paging, whole project using this version of recyclerview. forcing to use stable version of RecyclerView solve the problem.
在build.gradle中:
in build.gradle:
android { ... configurations.all { resolutionStrategy.eachDependency { details -> if (details.requested.group == 'androidx.recyclerview') { details.useVersion "1.1.0" } } } }更多推荐
如果使用Paging 3库,则onRestoreInstanceState不适用于RecyclerView布局管理器
发布评论