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.
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.
I believe the work beneath the list view is something like this (considering we have only one item view type):
do once:
inflate item view from layout, cache it
repeat for every item:
ask adapter to fill the data into the view
draw the view on the screen
move to next item
so you have the view which is inflated from xml layout and can be reused for drawing multiple list items. ViewHolder speeds it up a bit more by saving getViewById lookups.
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 View
s 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.