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

Kotlin中Unresolved reference: userId错误求助(Data Binding相关)

解决Kotlin中Unresolved reference: userId错误

错误详情

C:\Users\Paul\Documents\Projects\DataApp\app\src\main\java\com\example\dataapp\MyAdapter.kt: (19, 31): Unresolved reference: userId

问题出在MyAdapter的ViewHolder类中,XML布局已设置userId和title文本控件ID,但仍触发未解析引用错误。本人使用Data Binding(通过binding.root),而参考教程未使用Binding,怀疑是绑定配置问题。

排查方向与解决方案

1. 确认Data Binding启用状态

检查模块级build.gradle是否正确启用Data Binding:

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

同步项目后重新编译。

2. 验证布局文件的Binding根标签

确保布局文件最外层是<layout>标签,而非普通布局容器,示例:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/userId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</layout>

3. 检查ViewHolder中Binding对象的初始化

确保ViewHolder中正确初始化Binding实例,而非直接使用findViewById:

class MyAdapter : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
    inner class MyViewHolder(val binding: ItemLayoutBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(data: YourDataModel) {
            // 通过binding对象访问控件
            binding.userId.text = data.userId.toString()
            binding.title.text = data.title
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val binding = ItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MyViewHolder(binding)
    }
}

注:ItemLayoutBinding是布局文件名自动生成的类(布局文件名item_layout.xml对应ItemLayoutBinding)。

4. 清理缓存并重新编译

  • 执行Build > Clean Project
  • 执行Build > Rebuild Project
  • 重启Android Studio

错误原因分析

  • Data Binding未启用或布局未用<layout>包裹,导致自动生成的Binding类不存在,无法通过binding.userId访问控件
  • ViewHolder中未正确初始化Binding对象,仍尝试直接引用控件ID(非Binding方式)
  • 缓存问题导致生成的Binding类未更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:15:45