我在保存 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, 在返回片段时自动排列项目