为何ViewHolder模式的工作原理?工作原理、模式、ViewHolder

2023-09-12 08:08:53 作者:南城以南溫暖如初

我学会了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.

但它是如何工作的?适配器通常用来显示视图(集团)s的名单,如果我缓存查看,他们为什么不全部参照历史最悠久的一个?

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如何工作的最好的解释,看看罗曼盖伊的谷歌I / O 2009年讲起的 的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.

总之,适配器作为基础数据和的ViewGroup 之间的联系。以充满整个屏幕需要,它会使许多查看秒。当滚动或推送查看任何其他事件不在屏幕的适配器将重复使用查看,充满了正确的数据,以在屏幕上呈现。

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,视图中查看,ViewGroup中父)方法将使用权查看在任何时间,不管你的布局。我不知道这样做的内部,但我敢肯定,你可以浏览源$ C ​​$ C任何适配器(如ArrayAdapter.java)如果你有兴趣。 该 ViewHolder 只是保持一个指向浏览 view.findViewById所获得的(INT ID )。这是适配器的责任得到相应任意位置正确的数据。

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.

幻灯片11至13 罗曼的presentation 将使其有更多比什么我可以明确写。

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