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

RecyclerView Adapter中findViewById返回null问题求助

RecyclerView组件引用返回Null的解决方案

嘿,我一眼就看到问题出在哪儿啦!你在Adapter的onCreateViewHolder方法里加载错布局文件了😅

核心问题

你当前在onCreateViewHolder中加载的是页面级布局R.layout.activity_student_list,但实际上应该加载单个列表项的布局——也就是你贴出来的那个包含itemImage和itemText的LinearLayout布局(请替换成你实际保存该布局的文件名,比如student_row.xml)。

因为加载了错误的布局,ViewHolder里通过findViewById自然找不到对应ID的组件,所以返回Null。

修正后的Adapter代码

StudentListAdapter(val list:ArrayList<Student>, internal var newInstance: onItemClickListener) : RecyclerView.Adapter<StudentListAdapter.StudentViewHolder>(){
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder {
        // 这里改成你学生行布局的正确ID!
        val view = LayoutInflater.from(parent.context).inflate(R.layout.student_row, parent, false)
        return StudentViewHolder(view)
    }

    override fun getItemCount(): Int{
        return list.size
    }

    override fun onBindViewHolder(holder:StudentViewHolder, position: Int) {
        holder.title.text = list[position].name
        holder.image.setImageResource(list[position].image)
        holder.itemView.setOnClickListener {
            newInstance.onItemClick(list[position])
        }
    }

    class StudentViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        internal var title: TextView
        internal var image:ImageView
        init{
            image = itemView.findViewById(R.id.itemImage)
            title = itemView.findViewById(R.id.itemText)
        }
    }
}

额外排查小贴士

  • 确认你的学生行布局文件名没有拼写错误,比如大小写、后缀名是否正确
  • 检查布局文件里的android:id是否和ViewHolder中findViewById的ID完全一致(包括大小写)
  • 如果后续还有问题,可以在onCreateViewHolder中打印加载的布局对象,确认是否正确加载了目标布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:34:38