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

Android开发RecyclerView Item无显示问题排查求助

问题原因

RecyclerView不显示Item主要由以下2个核心错误导致,还有额外的代码问题需要同步修复:

  • 核心错误1:NotificationPanelRecViewAdapter中的getItemCount方法固定返回0,RecyclerView判定没有需要渲染的数据,自然不会加载任何Item。
  • 核心错误2:onCreateViewHolder填充布局时传入null作为父布局,会导致Item根布局的布局参数失效,即使触发渲染也可能出现宽高异常。
  • 额外问题:Spinner的适配器创建后没有绑定到对应控件,后续Spinner也无法正常显示选项;MainActivity中重复声明adapter变量属于冗余代码。

修复步骤

1. 修复getItemCount方法

将NotificationPanelRecViewAdapter中的getItemCount返回值修改为数据集的实际大小:

@Override
public int getItemCount() {
    return notificationPanel.size();
}

2. 修正布局填充逻辑

修改onCreateViewHolder中的inflate参数,传入父布局保证布局参数正常生效:

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    // 替换原来的null为parent
    View view = inflater.inflate(R.layout.notification_panel_cardview, parent, false);
    return new ViewHolder(view);
}

3. 修复Spinner绑定逻辑

在ViewHolder的构造方法中给Spinner设置适配器,解决后续Spinner无数据问题:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(mContext,R.array.hoursSpinnerValues, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hoursSpinner.setAdapter(adapter);

4. 可选优化(建议修改)

优化RecyclerView宽高适配

将activity_main.xml中RecyclerView的layout_width修改为match_parent,避免内容宽度适配异常:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/notificationPanelRecView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:visibility="visible" />

清理冗余代码

MainActivity中已经声明了全局的adapter变量,不需要再在onCreate里重新定义局部变量,直接给全局变量赋值即可:

// 删掉前面的NotificationPanelRecViewAdapter声明,直接用全局变量
adapter = new NotificationPanelRecViewAdapter(this);
adapter.setNotificationPanel(notificationPanel);

修改完成后重新运行即可看到Item正常显示。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:24:02