Layout Managers — The real culprit that adds complexity
I had a lotta trouble in the beginning in understanding the functioning and working of the recyclerview. The most common one was who is calling the onCreateViewHolder() and onBindViewHolder()? Is it the widget itself? Is the adapter calling it?
After a thorough investigation in the android developer guides, I found out why i was not able to wrap my head around the entity that is called the recyclerview. As you can assume from the title, it is the layout manager, that we pass to our recyclerview widget, that calls all of these functions in the adapter. Let me break it down what is happening in this call stack:
- Our <RecyclerView> widget gets inflated when the activity or the fragment gets setup up.
- During the setting up procedure, we add layout managers, adapters, item decorators, etc. to our recyclerview to make it more fancy. We also pass the dataSet that will be used by the adapter to inject information in viewholders during this step.
- Now our layout manager calculates the size of the screen and establishes that, let’s say, it needs 10 viewholders to project on the screen. In doing so, it calls the recyclerview adapter onCreateViewHolder(parent, type), by passing the parent and the type of viewholder it needs.
- onCreateViewHolder() spits out 10 empty ViewHolders. But, we have no use of 10 empty ViewHolders. So now the layout manager calls onBindViewHolder(viewHolder, position) by passing the empty ViewHolder and the position of the empty ViewHolder on the screen. Notice how layout manager does not know at what position what data is. It simply returns the ViewHolders position in the screen.
- Remember the dataSet we passed in to the adapter in step-2. Well that is simply the data that will be presented by these empty viewholders. From here on our job is easy now. All we need to do is get the respective data at the position that its corresponding ViewHolder is and attach that data to the widgets present in the ViewHolder.
- onBindViewHolder() starts injecting the information in these empty ViewHolders and when they get injected, the adapter simply returns these complete ViewHolders back to the Layout Manager.
- Now the Layout Manager simply takes these ViewHolders and display them on the screen.
Once you understand the way calls are being made, understanding recyclerview becomes super easy.
Layout Manager calls →RecyclerView.Adapter to give 10 ViewHolders.
RecyclerView.Adapter calls →onCreateViewHolder() to spit out 10 empty ViewHolders.
RecyclerView.Adapter passes →10 empty ViewHolders back to Layout Manager.
LayoutManager calls →RecyclerView.Adapter to inject data in these 10 empty ViewHolders.
RecyclerView.Adapter calls →onBindViewHolder() to inject data in these 10 empty ViewHolders.
RecyclerView.Adapter passes →10 complete ViewHolders back to Layout Manager.
Layout Manager displays these 10 complete ViewHolders on the screen.