When onBindViewHolder is called and how it works?

I am a beginner and I am having trouble with understanding a piece of code. Can someone please explain me when this function evoke and what is it for?

Here is my code :

    public void onBindViewHolder(myViewHolder holder, int position) {

        RecViewHolder currentdata = data.get(position);
        holder.favChecker = currentdata.getFavChecker();
        holder.serialID = currentdata.getSerialID();
        holder.theClassName = currentdata.getTheClassName();
}

Let me start with just a little bit of background (which you may already understand, but it's needed to explain onBindViewHolder()).

RecyclerView is designed to display long lists (or grids) of items. Say you want to display 100 rows of something. A simple approach would be to just create 100 views, one for each row and lay all of them out. But that would be wasteful, because most of them would be off screen, because lets say only 10 of them fit on screen.

So RecyclerView instead creates only the 10 views that are on screen. This way you get 10x better speed and memory usage. But what happens when you start scrolling and need to start showing next views?

Again a simple approach would be to create a new view for each new row that you need to show. But this way by the time you reach the end of the list you will have created 100 views and your memory usage would be the same as in the first approach. And creating views takes time, so your scrolling most probably wouldn't be smooth.

This is why RecyclerView takes advantage of the fact that as you scroll and new rows come on screen also old rows disappear off screen. Instead of creating new view for each new row, an old view is recycled and reused by binding new data to it.

This happens exactly in onBindViewHolder(). Initially you will get new unused view holders and you have to fill them with data you want to display. But as you scroll you'll start getting view holders that were used for rows that went off screen and you have to replace old data that they held with new data.


It is called by RecyclerView to display the data at the specified position. This method is used to update the contents of the itemView to reflect the item at the given position.

for more info check RecyclerView.Adapter#onBindViewHolder