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

Kotlin中RecyclerView仅显示单个Item问题求助

Why Your RecyclerView Only Shows One Item (Kotlin)

Hey there! Looking at your adapter code, the data part checks out—you’ve got 3 items in mData, and getItemCount() is returning the correct size. So the issue is almost definitely in your layout files, not the adapter itself. Let’s go through the most common fixes:

1. Fix Your Item Layout Height (cardview_items.xml)

This is the #1 reason for this problem. If your item’s root view (like the CardView) has android:layout_height="match_parent", each item will take up the entire screen, hiding the others. Swap that out for wrap_content so each item only takes as much space as it needs.

Here’s what that looks like:

<!-- ❌ Bad: Takes full screen height -->
<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- Your image and text views here -->
</androidx.cardview.widget.CardView>

<!-- ✅ Good: Wraps content -->
<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <!-- Your image and text views here -->
</androidx.cardview.widget.CardView>

2. Double-Check Your RecyclerView Setup

Make sure you’ve assigned a layout manager to your RecyclerView in your activity/fragment code. Without one, RecyclerView won’t know how to arrange items properly. Add this line when initializing your RecyclerView:

recyclerView.layoutManager = LinearLayoutManager(context)

(You can use GridLayoutManager or StaggeredGridLayoutManager too, depending on your needs.)

3. Watch for Nested Layouts with Fixed Heights

If your item layout has a parent container (like a LinearLayout or ConstraintLayout) set to match_parent height, that’ll also cause the item to fill the screen. Ensure all parent views in cardview_items.xml use wrap_content for height, or set proper constraints if you’re using ConstraintLayout.

4. Confirm Your Data Isn’t Being Modified

While your adapter’s mData has 3 items, it’s worth double-checking if something else in your code is clearing or truncating the list after the adapter is set. Add a quick log to getItemCount() to verify it’s returning 3 when the RecyclerView loads:

override fun getItemCount(): Int {
    Log.d("MyAdapter", "Total items: ${mData.size}")
    return mData.size
}

If the log shows 3, then data isn’t the issue.

Start with checking the item layout height—that’s almost always the problem here. Let me know if that fixes it!

内容的提问来源于stack exchange,提问作者임세준

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:32:47