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

Kotlin中使用LayoutInflater无法访问RecyclerView适配器的视图元素

问题原因

你无法直接通过v.id访问布局内控件,是因为inflate返回的View对象本身没有对应子控件的ID属性,需要通过合法的控件查找方式获取子视图实例。

解决方案

方案1:使用findViewById(传统写法)

首先定义ViewHolder类,在ViewHolder中绑定控件:

class CustomerAdapter(mCtx:Context,val customers:ArrayList<Customer>):RecyclerView.Adapter<CustomerAdapter.ViewHolder>(){

    // 自定义ViewHolder,存储列表项控件实例
    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // 替换成你布局里实际的控件ID和类型
        val txtCustomerName: TextView = itemView.findViewById(R.id.txt_customer_name)
        val txtCustomerPhone: TextView = itemView.findViewById(R.id.txt_customer_phone)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.lo_customers, parent, false)
        return ViewHolder(v)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val customer = customers[position]
        // 在onBindViewHolder中给控件赋值
        holder.txtCustomerName.text = customer.name
        holder.txtCustomerPhone.text = customer.phone
    }

    override fun getItemCount(): Int = customers.size
}

方案2:使用ViewBinding(推荐写法,避免空指针和类型转换错误)

  1. 先在模块级build.gradle.kts(或build.gradle)中开启ViewBinding:
// build.gradle.kts 配置
android {
    buildFeatures {
        viewBinding = true
    }
}
  1. 适配器适配ViewBinding写法:
class CustomerAdapter(val customers:ArrayList<Customer>):RecyclerView.Adapter<CustomerAdapter.ViewHolder>(){
    // 使用布局生成的Binding类,命名规则为布局名大驼峰+Binding后缀,比如lo_customers.xml生成LoCustomersBinding
    inner class ViewHolder(val binding: LoCustomersBinding) : RecyclerView.ViewHolder(binding.root)

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val customer = customers[position]
        // 直接通过binding访问控件,不需要手动findViewById
        holder.binding.txtCustomerName.text = customer.name
        holder.binding.txtCustomerPhone.text = customer.phone
    }

    override fun getItemCount(): Int = customers.size
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:06:02