setRecycledViewPool method in RecyclerView

setRecycledViewPool(...) can be useful when we have a nested RecyclerView. See this blog post for details. A short description of the same link is added here.

Consider a case where you have a nested RecyclerViews and inner RecycleViews share the same view structure. RecycledViewPool provides a seemless way to share views between these inner (nested) RecyclerViews.

An example of such case could be seen in the following image:

enter image description here

As you can see the types of views for both lists are same.


When the RecyclerView is expected to show more than 5 views on the screen at the same time (5 is the current default), it's recommended to enlarge it to what you think will be the max. This will allow to do an actual recycling (the purpose of RecyclerView...) when scrolling, to avoid re-creation of Views.

In fact, because I actually think that it's almost never known how many will be be shown on the screen (different screens resolutions, etc...) , I think it's best to just set it to be the max :

fun RecyclerView.setMaxViewPoolSize(maxViewTypeId: Int, maxPoolSize: Int) {
    for (i in 0..maxViewTypeId)
        recycledViewPool.setMaxRecycledViews(i, maxPoolSize)
}

Usage:

    recyclerView.setMaxViewPoolSize(MAX_TYPE_FOR_THE_ADAPTER_YOU_MADE, Int.MAX_VALUE)

I personally don't understand why it's not the default behavior. The whole point of using a RecyclerView is to recycle the Views. When scrolling, it should, by default, recycle views that were just used.


From docs:

Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views. This can be useful if you have multiple RecyclerViews with adapters that use the same view types, for example if you have several data sets with the same kinds of item views displayed by a ViewPager.

By default, 5 ViewHolders are retained in the pool for a particular viewType. If you want to change that count, it may be done this way:

recyclerView.getRecycledViewPool()
            .setMaxRecycledViews(SOME_VIEW_TYPE, POOL_CAPACITY);

From this blog post:

So how do we choose the optimal size of the pool? It seems that the optimal strategy is to extend the pool right before you’ll need it to be big, and shrink it right afterwards. One dirty way to implement this is the following:

recyclerView.getRecycledViewPool().setMaxRecycledViews(0, 20);
adapter.notifyDataSetChanged();
new Handler().post(new Runnable() {
    @Override
    public void run() {
        recyclerView.getRecycledViewPool()
                    .setMaxRecycledViews(0, 1);
    }
});