android - 如果使用 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, 在返回片段时自动排列项目
解决方案
更新:
我的问题通过使用解决了:
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"
}
}
}
}
推荐阅读
- if-statement - 从 Tableau 中的表中排除多个值
- python - 由于内存错误,无法在 Python 中将大型 JSON 文件解析为 Pandas DataFrame
- vba - 将文本框值分配给多个表/查询字段值
- javascript - CKEditor下的添加按钮不可见
- python - 使用带有 matplotlib.animation.ArtistAnimation() 的 .save() 方法保存 .gif IndexError
- r - 使用R中的for循环将多个变量转换为数字
- clips - 为什么没有很好地引用变量 x?
- amazon-web-services - 用于简单服务的 AWS 数据库
- javascript - 倒数第二次未返回承诺时调用递归承诺时遇到问题
- php - Preg 匹配 mustache lambdas 和其他“复杂”的 mustache 变量