为什么我们实际上使用LayoutInflater.from?为什么我们不能直接使用LayoutInflater.inflate?

时间:2020-07-20 04:08:13

标签: java android android-studio kotlin

任务是实现数组适配器的getView方法。每次对视图进行充气,在充气的视图中填充各个视图的内容,然后返回该视图。该方法的实现如图所示

private val inflater: LayoutInflater = LayoutInflater.from(context)

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
    
    val view = inflater.inflate(resource, parent, false) 

    val tvName : TextView = view.findViewById(R.id.tvName)
    val tvArtist : TextView = view.findViewById(R.id.tvArtist)
    val tvSummary : TextView = view.findViewById(R.id.tvSummary)

    val values = data[position]

    tvName.text = values.name
    tvArtist.text = values.artist
    tvSummary.text = values.summary

    return view
}

请向我解释为什么我们使用LayoutInflater.from(context)方法。难道我们只是使用LayoutInfater.inflate来做到这一点吗?我搜索了解释,并回答了一个答案:“ LayoutInflater.from将从给定上下文返回LayoutInflater对象。”我不明白。如果有人可以帮助我解决这个问题。

2 个答案:

答案 0 :(得分:3)

LayoutInflator是用于在视图中膨胀布局的类。

它包含几种方法,例如inflate()。

要调用这些方法,您需要LayoutInflator对象,该对象不能像“ new LayoutInflator()”那样创建。首先需要一个上下文来创建它的对象。

因此,LayoutInflator.from(context)返回一个LayoutInflator对象。使用它来调用其成员函数,例如“ inflate()”。

也许,这消除了您的疑问。

答案 1 :(得分:2)

LayoutInflater.from()是一种静态方法,它在给定LayoutInflater的情况下创建Context实例。由于这是一个静态方法,因此我们可以使用类名来调用它。另一方面,LayoutInflator.inflate()是一种非静态方法。这意味着我们需要引用LayoutInflater实例来调用它。我们不能直接在课堂上称呼它。如果您更改

val view = inflater.inflate(resource, parent, false)

val view = LayoutInflater.inflate(resource, parent, false)

您将收到类似这样的错误消息

不能从静态上下文中调用非静态方法

相关问题