How does Recycler view draw individual rows

Viewed 168

As per my understanding, the following things happen on a broad level when data is to be shown using the RecyclerView.

1) Recycler view calls the onCreateViewHolder() method which returns a ViewHolder object and then calls onBindViewHolder() which binds the data with individual views contained in the ViewHolder.

Doubt: As RecyclerView object never gets the total inflated View of the XML file, It only gets the views wrapped inside the ViewHolder object. How is RecyclerView able to draw the ViewHolder views correctly? Do the individual Views present in the ViewHolder have sufficient information about their parent layout, padding, margin, where they should be placed in their parent layout?

2 Answers

RecyclerView contains some components.

  1. Adapter (Provide data)
  2. View Holder (Provide view for binding data)
  3. LayoutManager (Locate position of each item)
  4. and others.

You could read this article to deep inside RecyclerView. (Link)

The main point which I missed here is that the custom ViewHolder class which we define is an extended version of base class RecyclerView.ViewHolder class which holds the actual reference to the inflated View. The constructor of this class receives the View object reference which we created by inflating the XML file of the row to be displayed. Hence this View object which represents the entire hierarchy of the row file layout is saved as an instance member which is named as itemView in the android defined base class (RecylclerViewer.ViewHolder).

class MyViewHolder extends RecyclerView.ViewHolder
{

    MyViewHolder(View itemView)
    {
        /* We are calling the base class constructor passing the Entire View hirerachy */
        super(itemView) 
    }
}

When we extend the ViewHolder class, we add additional View members in this class (like TextView, Buttons etc.) which is an optimisation so that while binding the data in onBindViewHolder(), we can avoid calls to findViewById on the parent View object. Thus our custom ViewHolder object not only wraps the sub view objects but also holds / wraps the reference to the entire inflated View. Because of this, RecyclerView is able to draw the row completely.

Related