You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Retrofit加载数据实现嵌套RecyclerView时内层列表不显示无报错求助

问题原因及修复方案

1. 内层RecyclerView约束错误(最核心原因)

外层条目item_outer_recycler中的内层RecyclerView约束配置错误:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/innerRecycler"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="parent" />

app:layout_constraintTop_toBottomOf="parent"表示将内层RecyclerView的顶部对齐到父布局的底部,直接被放到了外层条目的可视区域之外,自然无法显示。
修复方案:将内层RecyclerView的顶部约束到外层条目中最后一个可视控件的底部,比如布局里的houseAddress底部,同时补全横向约束:

app:layout_constraintTop_toBottomOf="@id/houseAddress"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginVertical="10dp" <!-- 可按需调整边距 -->

同时要确保外层条目里的houseName、houseAddress、houseHomepage这些控件的约束都配置完整,避免位置错乱。

2. 内层条目布局尺寸配置错误

内层RecyclerView的条目item_inner_recycler根布局尺寸配置不合理:

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

作为横向滚动的RecyclerView条目,宽度设为match_parent会导致单个条目占满整个RecyclerView的宽度,高度设为match_parent会让条目高度无限拉伸。
修复方案:修改根布局尺寸为wrap_content:

<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginEnd="8dp"> <!-- 可按需添加条目间距 -->

3. 内层适配器数据处理逻辑错误

你在MainTagAdapter的getItemCount方法里执行数据拆分操作,存在两个问题:

  • getItemCount会被RecyclerView频繁调用,重复拆分字符串属于冗余操作
  • Kotlin中split返回的是不可变List,强转成MutableList存在类型转换异常风险
  • 如果传入的tags是空字符串,拆分后得到空列表会导致内层RecyclerView无内容
    修复方案:在构造方法中提前处理数据:
class MainTagAdapter(private val data: String) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    // 构造时就完成数据拆分,空值兼容处理
    private val tagData = if (data.isNotBlank()) data.split(",") else emptyList()

    override fun getItemCount(): Int = tagData.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainTagHolder =
        MainTagHolder(ItemInnerRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val binding = (holder as MainTagHolder).binding
        binding.houseTag.text = tagData[position]
    }
}

4. 可选优化:内层RecyclerView配置顺序调整

外层适配器中设置内层RecyclerView时,建议先设置LayoutManager再设置Adapter,避免偶发的渲染异常:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    val house = data[position]
    val binding = (holder as MainHouseHolder).binding
    // 先设LayoutManager
    binding.innerRecycler.layoutManager =
        LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
    // 再设Adapter
    binding.innerRecycler.adapter = MainTagAdapter(house.tags)
    // 其余外层条目渲染逻辑保持不变
}

内容的提问来源于stack exchange,提问作者timothy jeong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:24:10