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

Android开发:RecyclerView仅显示Habits数组第一个元素故障排查

问题原因

你遇到的问题是两个布局配置错误共同导致的:

  • 单条卡片布局single_item.xml的根布局用了高度为match_parent的ScrollView,这会让每个列表项直接占满整个RecyclerView的可视高度,第一个条目直接占满全屏,如果你没有主动上滑页面,就会误以为只有一个条目显示。你交换两个条目的顺序后,排在前面的散步条目占满了屏幕,自然就看不到后面的喝水条目。
  • 主布局里的RecyclerView高度设为wrap_content,会导致RecyclerView测量异常,进一步加剧列表展示问题。

修复方案

1. 移除单条卡片布局外层多余的ScrollView

single_item.xml不需要单独加滚动容器,修改后代码如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="12dp"
    app:cardCornerRadius="12dp">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/image_view_icon"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_margin="8dp"
            android:scaleType="centerCrop"
            tools:src="@drawable/water" />

        <TextView
            android:id="@+id/text_view_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="12dp"
            android:layout_toEndOf="@id/image_view_icon"
            android:textSize="28sp"
            tools:text="Drink Water" />
        <TextView
            android:id="@+id/text_view_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:text="Drink Water"
            android:layout_toEndOf="@id/image_view_icon"
            android:layout_below="@id/text_view_title"
            android:layout_marginStart="8dp"/>

    </RelativeLayout>
</androidx.cardview.widget.CardView>

2. 修改主布局RecyclerView高度

把activity_main.xml里的RecyclerView的layout_height属性改成match_parent,避免测量异常:

<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    tools:listitem="@layout/single_item"
    android:id="@+id/recycler_view_list"/>

3. 可选优化

MainActivity里声明的itemBinding从未使用,可以直接删除,避免冗余警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:39:03