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

RecyclerView中无法使用LayoutInflater的原因与解决办法

问题背景

在自定义RecyclerView.Adapter的onCreateViewHolder方法中尝试使用LayoutInflater时,Android开发环境无法识别该类,不支持代码自动补全,但在Activity中LayoutInflater可以被正常识别、支持自动补全。
问题复现代码如下:

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

class MyAdapter(var ctx: Context): RecyclerView.Adapter<RecyclerView.ViewHolder> (){


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        var myRoot: layoutInflater
    }
}
问题原因
  • 类名书写错误:LayoutInflater是Android SDK提供的正式类,类名首字母必须大写,代码中写的小写开头layoutInflater既不是正确的类名,也不是当前Adapter类作用域内的可用属性/变量,IDE自然无法识别。
  • 作用域差异:Activity中可以直接使用小写layoutInflater,是因为AppCompatActivity/Fragment等系统组件本身实现了LayoutInflater相关接口,自带getLayoutInflater()方法,Kotlin语法会将该getter方法转换为可直接访问的layoutInflater属性;而自定义Adapter是独立的普通类,既没有继承对应系统组件,也没有定义该属性,无法直接访问。
  • 缺少类导入:就算写对了大写开头的LayoutInflater类名,如果没有在文件顶部添加对应导入语句,IDE也无法正常识别、触发自动补全。
解决方案
  • 补充正确导入:在文件顶部添加import android.view.LayoutInflater导入语句,使用类名时注意首字母大写。
  • 优先通过onCreateViewHolder的parent参数获取LayoutInflater实例,不需要额外给Adapter传入Context,避免持有Context引发内存泄漏,正确写法示例:
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
// 替换为你自己项目的布局对应R类/ViewBinding类导入路径
import com.yourapp.databinding.YourItemLayoutBinding

class MyAdapter: RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

    inner class MyViewHolder(val binding: YourItemLayoutBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        // 从父容器context获取LayoutInflater实例
        val inflater = LayoutInflater.from(parent.context)
        val binding = YourItemLayoutBinding.inflate(inflater, parent, false)
        return MyViewHolder(binding)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        // 实现对应位置的数据绑定逻辑
    }

    override fun getItemCount(): Int {
        // 返回列表数据源的总长度
        return 0
    }
}
  • 如果使用ViewBinding/DataBinding,也可以直接通过对应Binding类的inflate方法加载布局,不需要手动调用LayoutInflater.from(),底层实现逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 13:45:30