Search code examples
androidkotlinandroid-viewholder

Understanding the functionallity of onCreateViewHolder()


So I implemented this method based on a tutorial :

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TestAdapterHodl {
        
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_card, parent,false)
        return TestAdapterHodl(view)
    }

As far as I know, onCreateViewHolder() is called when the recycler needs a new viewHolder. The line:

val view = LayoutInflater.from(parent.context).inflate(R.layout.item_card, parent,false)

inflates the item_card.xml file for the viewHolder.

But I dont understand what .from(parent.context) does and what parent is. I would love to know it so I can understand it completely.


Solution

  • LayoutInfalter is the class that is responsible for instantiating XML views into their corresponding objects. It creates all the views. We never use it directly, instead, we get the already attached inflater to the context and use it to inflate layouts.

    But I dont understand what .from(parent.context)

    from(context) is a method of the LayoutInflater class that returns the inflater instance currently attached to the given context.

    what parent is

    parent is the RecyclerView to which you are setting this adapter.