为什么ViewHolder模式可以工作? [英] why does the ViewHolder pattern work?

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

问题描述

我今天学习了Android的ArrayAdapter,并发现有一个commom模式,它使用ViewHolder来保存Views的引用,而不是每次调用findViewById。



但是它如何工作?适配器通常用于显示View(Group)的列表,如果我缓存View,为什么不引用最老的?

解决方案

如果您想要了解ViewHolder如何工作的最佳解释,请查看Romain Guy的Google I / O 2009演讲,网址为 youtube ,特别是前15分钟。



简而言之,适配器作为底层数据和 ViewGroup 之间的链接。它将根据需要呈现尽可能多的查看,以填充屏幕。滚动或任何推送 View 的其他事件超出屏幕,适配器将重复使用查看,填充正确的数据,在屏幕上呈现。



getView(int pos,View view,ViewGroup parent)方法将使用正确的查看,无论您的布局如何。我不知道这些内容,但我相信你可以浏览任何适配器的源代码(例如 ArrayAdapter.java )如果你有兴趣的话。

ViewHolder 只是保留指向视图 view.findViewById(int id)获得。适配器的责任是返回对应于任何位置的正确数据。



幻灯片11到13的 Romain的演示文稿会比我写的东西要清楚得多。


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.

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?

解决方案

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.

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.

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.

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

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

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