Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the ViewHolder pattern work?

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?

like image 872
Lai Yu-Hsuan Avatar asked Jan 26 '26 22:01

Lai Yu-Hsuan


2 Answers

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.

like image 72
Aleadam Avatar answered Jan 29 '26 13:01

Aleadam


Sorry but denis' answer may be wrong. In fact, the view instances(and ViewHolders) are as many as your screen can display.

If your screen looks like:

[list view]
the first item
the second item
the third item
the fourth item

You will have 4 instances of views. If you scroll screen, the first will disappear but be pass to getItem() as convertView for you to create the fifth item.

So you can use the references in first ViewHolder.

like image 43
Lai Yu-Hsuan Avatar answered Jan 29 '26 12:01

Lai Yu-Hsuan