Roshan Nayak
Roshan Nayak

Reputation: 53

Why do we actually use LayoutInflater.from? Why cant we use LayoutInflater.inflate directly?

The task was to implement the getView method of the array adapter. Inflate a view each time, fill the contents of the individual views in the inflated view and then return the view. The method implementation was as shown

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
}

Please explain me why do we use the LayoutInflater.from(context) method. Cant we do it just using LayoutInfater.inflate? I searched for the explanation and one of the answers said "LayoutInflater.from will return a LayoutInflater object from the given context." Which I couldn't understand. If anyone could help me out with this.

Upvotes: 1

Views: 307

Answers (2)

Ankit Gupta
Ankit Gupta

Reputation: 544

LayoutInflator is a class used to inflate layout in the views.

It contains several methods, like inflate().

To invoke these methods you need LayoutInflator object, which you cannot create like "new LayoutInflator()". It needs a context first to create an object of it.

So, LayoutInflator.from(context) return you an LayoutInflator object. Using which you invoke its member functions like "inflate()".

Maybe, this clears your doubt.

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83577

LayoutInflater.from() is a static method that creates a LayoutInflater instance given a Context. Since this is a static method, we can call it using the class name. On the other hand LayoutInflator.inflate() is a non-static method. This means we need a reference to a LayoutInflater instance to call it. We cannot call it with the class directly. If you change

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

to

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

you will an error message something like

cannot call non-static method from a static context

Upvotes: 2

Related Questions