我希望我的RecyclerView不回收某些物品 [英] I want my RecyclerView to not recycle some items

查看:700
本文介绍了我希望我的RecyclerView不回收某些物品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RecyclerView,其中包含异构视图,本教程.

I'm using a RecyclerView with heterogeneous views inside, as seen in this tutorial.

我在RecyclerView中有一些项目也是RecyclerViews.很难想象?假设我要复制Play商店的布局:一个大的RecyclerView,具有垂直线性布局,并由许多元素填充:单个应用和应用轮播.

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.

如果要添加的项目是单个应用程序的布局,则将使用ID 1,我将添加单个项目的布局. 否则,如果我需要添加轮播,那么我将在主RecyclerView中添加一个元素:另一个具有自己的适配器的RecyclerView.

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.

效果很好.滚动主RecyclerView时除外.为什么?因为某些视图不再可见时将被销毁,然后在onBindViewHolder()方法中将其重新创建.为什么在这里?因为主RecyclerView的适配器正在传递位置X,然后调用OnBindViewHolder().然后,后者使用自己的适配器创建一个新的RecyclerView并将其分配给它.我只想保留这些观点,因为它们每次都会沉重地重新膨胀.

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?

推荐答案

使用此:

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

这不会回收viewType TYPE_CAROUSEL的任何视图,但是如果此类型的项目计数很高,那么它将显着降低您的性能,甚至可能导致OOMEs

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

编辑

阅读 MML13 的答案后,我认为它可能对您有用.在外部RecyclerView中重新绑定该视图时,您担心轮播的项目会重新膨胀.如果所有这些轮播都具有相同的类型,即它们都使用相同的适配器,则可以将适配器保留在外部RecyclerView的ViewHolder中,然后交换出数据并在重新绑定后在此适配器上调用notifyDataSetChanged()notifyItemRangeChanged(...).这将回收所有轮播视图以及这些轮播中的所有视图.

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.

这篇关于我希望我的RecyclerView不回收某些物品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆