【问题标题】:Why do we actually use LayoutInflater.from? Why cant we use LayoutInflater.inflate directly?为什么我们实际使用 LayoutInflater.from?为什么我们不能直接使用 LayoutInflater.inflate?
【发布时间】:2020-07-21 07:48:06
【问题描述】:

任务是实现数组适配器的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 对象。”我无法理解。如果有人可以帮助我解决这个问题。

【问题讨论】:

    标签: java android android-studio kotlin


    【解决方案1】:

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

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

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

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

    也许,这可以消除你的疑虑。

    【讨论】:

      【解决方案2】:

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

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

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

      你会看到类似的错误信息

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-25
        • 2020-11-11
        • 2011-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多