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

Kotlin中LayoutInflater.inflate报Unresolved reference错误求助

问题解决与代码优化

原错误原因

直接调用LayoutInflater.inflate()是错误的,因为inflate是LayoutInflater类的实例方法,而非静态方法,必须先获取LayoutInflater的实例才能调用。你遇到的“Unresolved reference: inflate”错误,就是因为没有正确获取实例就调用方法导致的。

你修改后的代码问题

getLayoutInflater()是Activity类的专属方法,在自定义Adapter的getView方法里无法直接调用,这个修改会引发新的报错(比如“Unresolved reference: getLayoutInflater”),无法正常运行。

正确的实现方式

在Adapter的getView方法中,我们可以通过传入的ViewGroup参数(p2)的Context来获取LayoutInflater实例,同时要复用convertView(p1)提升列表性能,正确代码如下:

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    var myView = convertView
    // 复用convertView,避免重复解析布局
    if (myView == null) {
        val inflater = LayoutInflater.from(parent?.context)
        // 第三个参数传false,避免自动将布局添加到parent,由ListView自行处理
        myView = inflater.inflate(R.layout.row_custom_listitem, parent, false)
    }
    val myNote = listNotes[position]
    // 若未配置kotlin-android-extensions插件,需用findViewById获取控件
    myView?.findViewById<TextView>(R.id.tvTitle)?.text = myNote.noteName
    myView?.findViewById<TextView>(R.id.tvDes)?.text = myNote.noteDes
    return myView!!
}

额外提示

  • 如果你之前用myView.tvTitle的写法能运行,说明开启了kotlin-android-extensions插件,但该插件已被废弃,推荐使用ViewBinding替代,更安全且性能更优。
  • 传入parent作为inflate的第二个参数、第三个参数设为false是标准写法,能保证布局的LayoutParams正确应用,避免显示异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 07:54:22