为什么 ViewHolder 模式有效? [英] why does the ViewHolder pattern work?

查看:23
本文介绍了为什么 ViewHolder 模式有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天学习了 Android 的 ArrayAdapter,发现有一个通用模式,它使用 ViewHolder 来保存视图的引用,而不是每次都调用 findViewById.

I learned Android's ArrayAdapter today, and find there is a commom pattern which uses a ViewHolder to hold Views' reference instead of calling findViewById everytime.

但是它是如何工作的呢?Adapter 通常用于显示一个 View(Group) 的列表,如果我缓存了 View,为什么它们不都引用最旧的一个?

But how does it work? Adapter is usually used to display a list of View(Group)s, If I cache the View, why don't they all reference to the oldest one?

推荐答案

如果您想获得有关 ViewHolder 如何工作的最佳解释,请查看 youtube,特别是前 15 分钟.

If you want the best explanation on how the ViewHolder works, check out Romain Guy's Google I/O 2009 talk in youtube , specially the first 15 minutes.

简而言之,Adapter 充当底层数据和 ViewGroup 之间的链接.它将根据需要渲染尽可能多的 View 以填充屏幕.在滚动或任何其他将 View 推送到屏幕之外的事件时,Adapter 将重用该 View,填充正确的数据,要在屏幕上呈现.

In short, the Adapter functions as a link between the underlying data and the ViewGroup. It will render as many Views as required to fill the screen. Upon scrolling or any other event that pushes a View is out of the screen, the Adapter will reuse that View, filled with the correct data, to be rendered at the screen.

getView(int pos, View view, ViewGroup parent) 方法将在任何时候使用正确的 View,无论您的布局如何.我不知道它的内部原理,但我确定您可以浏览任何适配器的源代码(例如 ArrayAdapter.java) 如果您有兴趣.
ViewHolder 只保留一个指向 Views 的指针,由 view.findViewById(int id) 获得.Adapter 负责返回任何位置对应的正确数据.

The getView(int pos, View view, ViewGroup parent) method will use the right View at any time, regardless of your layout. I do not know the internals of this, but I'm sure you can browse the source code for any adapter (such as ArrayAdapter.java) if you're interested.
The ViewHolder just keeps a pointer to the Views as obtained by view.findViewById(int id). It is the Adapter responsibility to return the right data corresponding to any position.

Romain 的演示文稿的幻灯片 11 到 13 将使它比任何事情都清楚我可以写.

Slides 11 to 13 of Romain's presentation will make it a lot more clear than anything I can write.

这篇关于为什么 ViewHolder 模式有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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