I am trying to understand what the setRecycledViewPool method actually does along with the RecyclerView in the following line of code where mrecyclerView
is a R
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 ViewHolder
s 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);
}
});
I haven't used it myself, but from what I can understand reading the docs its a way to use views you recycle in one RecyclerView with another.
So if you have a RecyclerView with a bunch of decked out CardViews, and you would like to recycle those same views for another RecyclerView you could pass it a shared RecycledViewPool. Now both RecyclerView will take from the shared view pool.
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.
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 RecyclerView
s and inner RecycleView
s share the same view structure. RecycledViewPool
provides a seemless way to share views between these inner (nested) RecyclerView
s.
An example of such case could be seen in the following image:
As you can see the types of views for both lists are same.