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

查看:41
本文介绍了我希望我的 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,我将为单个项目添加布局.否则,如果我需要添加一个 Carousel,那么我将向主 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 的 Adapter 正在为位置 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);

这不会回收viewTypeTYPE_CAROUSEL的任何视图,但是如果这个类型的item数非常高,那么它会显着降低你的性能,甚至可能导致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天全站免登陆