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

RecyclerView不显示条目,已确认Adapter被调用但无内容渲染求排查

问题1:Adapter构造函数赋值逻辑错误(核心原因)

你写的Adapter构造函数存在两个致命错误:

  • 成员变量和参数同名的情况下没有加this关键字区分,导致赋值的是参数而不是类成员
  • 赋值逻辑完全混乱,两个列表参数最终都没有正确赋值给类成员,成员变量mTextViewItem始终是空数组,mTextViewText始终是null,所以getItemCount返回0,自然不会渲染任何条目

修正后的构造函数代码:

public RecyclerViewAdapter(Context context, ArrayList<String> mTextViewItem, ArrayList<String> mTextViewText) {
    this.mTextViewItem = mTextViewItem;
    this.mTextViewText = mTextViewText;
    this.mContext = context;
}

问题2:RecyclerView初始化和Adapter设置逻辑放在循环中

你当前把findViewById、设置布局管理器、设置Adapter的逻辑都写在了遍历Cursor的do-while循环里,会导致每遍历一条数据就重新初始化一次RecyclerView、重新创建Adapter,不仅严重影响性能,还可能出现显示异常。正确的逻辑是循环只负责往列表里加数据,所有初始化逻辑放在循环外。

修正后的遍历代码:

// 先初始化RecyclerView,只做一次
recyclerView = root.findViewById(R.id.RecyclerPesquisa);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); // 不要用ApplicationContext,直接用Activity上下文避免布局主题异常
mTitulo.clear();
mTexto.clear();

if (cursor != null && cursor.moveToFirst()) {
    do {
        Integer id = cursor.getInt(0);
        String nome = cursor.getString(1);
        String receita = cursor.getString(2);
        mTitulo.add(nome);
        mTexto.add(receita);
    } while (cursor.moveToNext());
    // 数据全部加载完成后再设置Adapter
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), mTitulo, mTexto);
    recyclerView.setAdapter(adapter);
}
// 用完记得关闭Cursor避免内存泄漏
if (cursor != null) {
    cursor.close();
}

额外排查点

如果修正后还是不显示,可以检查R.layout.layout_list条目布局的根布局高度是不是设置成了match_parent,如果是的话改成wrap_content,否则单个条目占满整个屏幕,看起来就像只显示了一条或者没显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:48:02