仅将 RecyclerView 中的视图动态添加到当前项目 [英] Dynamically adding Views in a RecyclerView only to current item

查看:39
本文介绍了仅将 RecyclerView 中的视图动态添加到当前项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将视图动态添加到 RecyclerView 中的项目中.这些添加的视图应该只与添加它们的项目相关,但是我在滚动时遇到了问题.似乎 View 被回收并加载了一个新项目,但那些以前添加的视图仍然存在,只是现在在错误的项目上.

I'm dynamically adding Views to my items in a RecyclerView. These added Views should only be related to the item which they're added to, but I'm having a problem when I scroll. It seems the View is recycled and a new item is loaded, but those previously added views are still there, only now on the wrong item.

我假设这只是因为 ViewHolder 被重用,所以添加的项目在加载时再次显示新项目.

I'm assuming that it's just because the ViewHolder is being reused, so the added items show up again with a new item, when loaded.

如何解决这个问题?

推荐答案

这是我的一个老问题.悬赏金悬赏了它,因此人气飙升,并出现了多个新的、无关紧要的答案.

This was an old question of mine. A bounty was placed on it, hence the surge of popularity and the multiple new and irrelevant answers.

正如我对这个答案的评论和下面@CQM的评论中所述我原来的问题,答案是覆盖 onViewRecycled() 方法并在那里执行任何需要的操作.回收视图时调用此方法,任何清理操作都可以在这里完成.

As stated in both my comment to this answer and @CQM's comment below my original question, the answer is to override the onViewRecycled() method and perform any needed operations there. This method is called when a view is recycled, and any cleanup operations can be done here.

可以找到有关此方法的文档此处.

Documentation on this method can be found here.

就我而言,这是删除附加到视图的不可见 TextView 的问题.案文本身已被删除,但观点仍然存在.如果许多不可见的 TextView 堆积在视图上并且在滚动时没有正确回收,滚动将开始滞后.

In my case, it was a matter of deleting the invisible TextView's attached to the view. The text itself had been deleted, but the view remained. If many invisible TextView's accumulate on the view and aren't properly recycled when scrolling, the scroll will begin to lag.

这篇关于仅将 RecyclerView 中的视图动态添加到当前项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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