Kotlin中使用Volley库的RecyclerView不显示数据问题排查
问题排查与修复方案
核心问题1:RecyclerView始终处于隐藏状态
在activity_contact.xml中,RecyclerView初始可见性被设为gone,且获取数据成功后仅隐藏了ProgressBar,未将RecyclerView切换为可见状态,导致它一直无法显示。
修复:在getData()方法的成功回调中添加可见性设置:
loadingPB.visibility = View.GONE courseRV.visibility = View.VISIBLE // 新增此行代码
核心问题2:RecyclerView未配置LayoutManager
RecyclerView必须指定LayoutManager才能正确布局列表项,你的代码仅设置了Adapter,缺少关键的LayoutManager配置,这会导致即使RecyclerView显示,也无法渲染子项。
修复:在ContactActivity的onCreate方法中添加LayoutManager设置:
// 为RecyclerView设置适配器 courseRV.adapter = courseRVAdapter // 新增:设置线性布局管理器 courseRV.layoutManager = LinearLayoutManager(this)
次要问题:Item布局存在语法错误
course_rv_item.xml的CardView标签里包含无效内容enter code here,会导致布局解析失败:
<androidx.cardview.widget.CardView enter code herexmlns:android="http://schemas.android.com/apk/res/android"
修复:删除多余内容,修正为:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
额外优化建议
- 避免在循环中频繁调用
notifyDataSetChanged(),可在循环结束后统一调用一次,提升性能:
for (i in 0 until response.length()) { val respObj = response.getJSONObject(i) val langName = respObj.getString("sliderTitle") val langImg = respObj.getString("sliderImage") courseList.add(CourseRVModal(langName, langImg)) } // 循环结束后统一通知适配器更新 courseRVAdapter.notifyDataSetChanged()
- 后续可考虑使用
DiffUtil实现更高效的数据更新,替代全量刷新。
内容的提问来源于stack exchange,提问作者Captain SK
相关产品推荐
相关产品推荐

