I'm using a RecyclerView
with heterogeneous views inside, as seen in this tutorial.
I have some items inside that RecyclerView that are RecyclerViews too. Too hard to imagine? Let's say I want to copy the Play Store's layout: One big RecyclerView with vertical linear layout and filled by many elements: Single apps and carousel of apps.
If the item to add is the layout for a single app then ID 1 will be used and I will add the layout for a single item. Else, if I need to add a Carousel then I will add one element to the main RecyclerView: Another RecyclerView with its own adapter.
That works very well. Except when you scroll the main RecyclerView. Why? Because some views are being destroyed when no more visible and then recreated in the onBindViewHolder()
method. Why here? Because the Adapter of the main RecyclerView is passing for the position X and then calls OnBindViewHolder()
. The latter then creates a new RecyclerView with its own adapter and assigns it to it. I'd like to keep those views just because they are heavy to reinflate every time.
Is this possible? If so, can you tell me how?
Use this:
recyclerView.getRecycledViewPool().setMaxRecycledViews(TYPE_CAROUSEL, 0);
This prevents views of type TYPE_CAROUSEL
from being recycled. However, if there are many such items, it can significantly impact performance and may even cause OutOfMemoryErrors (OOMEs).
If your adapter only has one type of view and you haven't overridden the getItemViewType(position: Int): Int
method, you can pass 0
as the first parameter to setMaxRecycledViews
. See this
EDIT
After reading MML13's answer, I believe their approach might work for you. Your concern is that carousel items are being reinflated when their view is rebound in the outer RecyclerView
. If all carousels use the same adapter, you can store the adapter inside the outer RecyclerView
's ViewHolder
. Then, instead of reinflating, simply update the adapter’s data and call notifyDataSetChanged()
or notifyItemRangeChanged(...)
when the view is rebound.
This ensures that both the carousel views and the items within them are properly recycled.