Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView is creating ViewHolders for all items at once

I have main RecyclerView which contains other RecyclerViews (let's call them subRecyclerViews). The number of subRecyclerViews is based on the data received from server. The problem is, that whenever a subRecyclerView is about to become visible, it creates ViewHolders for all its items at once (instead of creating ViewHolders only for visible items).

In my MainRecyclerViewAdapter onBindViewHolder() method I call

subRecyclerViewAdapter.setData(data);
subRecyclerView.notifyDataSetChanged();

which results in a lag, because the subRecyclerView is calling onCreateViewHolder() and onBindViewHolder() methods for all its items.

The version of RecyclerView I use is

com.android.support:recyclerview-v7:25.1.1

The question is, is there a way to tell subRecyclerView that it doesn't need to create ViewHolders for the items, that are not yet visible? Also, is this a bug in RecyclerView or am I doing something wrong?

like image 532
Mischmo Avatar asked Feb 03 '17 17:02

Mischmo


People also ask

How do you inflate multiple layouts using one recycler view?

If you need a view with different viewTypes, you can just write the Adapters for each section and just use ConcatAdapter to merge all of them inside one recyclerview.

How many times onCreateViewHolder called?

By default it have 5. you can increase as per your need. Save this answer.

Which methods you would override if you have to implement a RecyclerView having different types of views provide proper method names?

You will have to override two main methods: one to inflate the view and its view holder, and another one to bind data to the view. The good thing about this is that the first method is called only when we really need to create a new view. No need to check if it's being recycled.


1 Answers

A solution these days instead of using 'subRecyclerViews' is to use one recyclerView with a ConcatAdapter

val firstAdapter: FirstAdapter
val secondAdapter: SecondAdapter
val thirdAdapter: ThirdAdapter
val concatAdapter = ConcatAdapter(firstAdapter, secondAdapter, 
     thirdAdapter)
recyclerView.adapter = concatAdapter
like image 74
MSpeed Avatar answered Nov 15 '22 01:11

MSpeed