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 RecyclerView object:
mrecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
I read the Android documentation link and I still don't understand what it does clearly. Can someone explain to me its use and when to use it?
RecycledViewPool lets you share Views between multiple RecyclerViews. If you want to recycle views across RecyclerViews, create an instance of RecycledViewPool and use RecyclerView. setRecycledViewPool(RecycledViewPool) . RecyclerView automatically creates a pool for itself if you don't provide one.
RecyclerView makes it easy to efficiently display large sets of data. You supply the data and define how each item looks, and the RecyclerView library dynamically creates the elements when they're needed. As the name implies, RecyclerView recycles those individual elements.
onBindViewHolder. Called by RecyclerView to display the data at the specified position. This method should update the contents of the itemView to reflect the item at the given position. Note that unlike android.
Go to app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item. xml contains an ImageView and a TextView which is used for populating the 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 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.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With