Realme C3锁屏解锁后GridLayoutManager下RecyclerView不显示项疑问
RecyclerView锁屏解锁后GridLayoutManager下不显示项(仅Realme C3出现)
问题现象
- 首次进入Fragment时Adapter运行正常,锁屏再解锁后RecyclerView的Adapter项完全无法显示
- 打印集合大小和数据均正常,但屏幕无对应内容展示,调用
notifyDataSetChanged()也无效果 - 将GridLayoutManager替换为LinearLayoutManager后问题解决,且仅在Realme C3机型出现
绑定Adapter的代码
if (mDocUploadedImagesPathArrayList.size > 0){ binding.uploadedDocumentLayout.visibility = View.VISIBLE documentListAdapter = DoctorDocumentImageAdapter( requireActivity(), mDocUploadedImagesPathArrayList, this ) } else{ binding.uploadedDocumentLayout.visibility = View.GONE } val mlayoutManager = GridLayoutManager(requireActivity(), 3) binding.uploadedDocumentRecyclerview.layoutManager = mlayoutManager binding.uploadedDocumentRecyclerview.isNestedScrollingEnabled = false binding.uploadedDocumentRecyclerview.adapter = documentListAdapter
原因分析
Realme定制系统的GridLayoutManager兼容性bug
Realme C3搭载的Realme UI(基于Android 10/11)可能对GridLayoutManager的状态恢复逻辑存在定制化缺陷。锁屏解锁时,系统会触发视图生命周期的状态恢复流程,GridLayoutManager的内部布局缓存、子视图测量逻辑在这个过程中出现异常,导致无法正确渲染子项;而LinearLayoutManager的状态恢复逻辑更稳定,未触发该机型的特定bug。重复创建LayoutManager导致的状态冲突
你的代码每次都重新创建GridLayoutManager实例并设置给RecyclerView,锁屏解锁时,Fragment视图重建后新创建的LayoutManager无法正确读取之前保存的布局状态,进而导致布局计算异常,子项无法显示。LinearLayoutManager对这种重复设置的兼容性更好,因此未出现问题。嵌套滚动禁用与GridLayoutManager的适配问题
你设置了isNestedScrollingEnabled = false,Realme C3的系统在处理嵌套滚动禁用的GridLayoutManager时,锁屏解锁后的视图重绘流程出现异常,导致子视图未被正确测量和布局,而LinearLayoutManager不受此影响。
修复建议
- 复用LayoutManager实例:在Fragment的
onViewCreated中仅初始化一次GridLayoutManager,后续仅更新Adapter数据,避免重复设置导致状态冲突:private lateinit var mlayoutManager: GridLayoutManager override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mlayoutManager = GridLayoutManager(requireActivity(), 3) binding.uploadedDocumentRecyclerview.layoutManager = mlayoutManager binding.uploadedDocumentRecyclerview.isNestedScrollingEnabled = false } fun updateDocumentList(data: List<String>) { mDocUploadedImagesPathArrayList.clear() mDocUploadedImagesPathArrayList.addAll(data) if (mDocUploadedImagesPathArrayList.isNotEmpty()){ binding.uploadedDocumentLayout.visibility = View.VISIBLE if (binding.uploadedDocumentRecyclerview.adapter == null) { documentListAdapter = DoctorDocumentImageAdapter(requireActivity(), mDocUploadedImagesPathArrayList, this) binding.uploadedDocumentRecyclerview.adapter = documentListAdapter } else { documentListAdapter.notifyDataSetChanged() } } else{ binding.uploadedDocumentLayout.visibility = View.GONE } } - 强制触发布局刷新:如果必须重新设置LayoutManager,在设置后调用
binding.uploadedDocumentRecyclerview.requestLayout(),强制RecyclerView重新测量布局。
内容的提问来源于stack exchange,提问作者Anubhav Adhyayan
相关产品推荐
相关产品推荐

