Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want my RecyclerView to not recycle some items

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?

like image 806
Joaquin Iurchuk Avatar asked Mar 30 '16 15:03

Joaquin Iurchuk


People also ask

How do I remove spaces between items in RecyclerView?

Try to use cardElevation=0dp. This should remove the extra spacing between recyclerview items.

What is expandable RecyclerView?

Expandable RecyclerView is one of the most important feature in Android which can be easily created for our application . It contains two views one is parent view and other is child view. Parent is visible by default but the child view has to be expanded and collapsed. It will expand when we click on parent view.


2 Answers

Use this:

recyclerView.getRecycledViewPool().setMaxRecycledViews(TYPE_CAROUSEL, 0); 

This will not recycle any view of viewType TYPE_CAROUSEL but if the item count of this type is very high, then it will reduce your performance significantly, maybe even cause OOMEs

EDIT

After reading MML13's answer, I think it might work for you. You are worried about items of your carousel being reinflated when that view is rebinded in outer RecyclerView. If all those carousel's are of same type, i.e., they all use same adapter, you can keep the adapter inside outer RecyclerView's ViewHolder, and just swap out data and call notifyDataSetChanged() or notifyItemRangeChanged(...) on this adapter when it's rebinded. This will recycle all carousel views and all views inside those carousels.

like image 58
Sourabh Avatar answered Sep 22 '22 23:09

Sourabh


You can also set below code in your onBindViewholder() method of adapter.

holder.setIsRecyclable(false); 

I have taken reference from this link

http://aphoe.com/blog/prevent-androids-recyclerview-recycling-views/

like image 27
Yyy Avatar answered Sep 18 '22 23:09

Yyy