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
Adapterfunctions as a link between the underlying data and theViewGroup. It will render as manyViews as required to fill the screen. Upon scrolling or any other event that pushes aViewis out of the screen, theAdapterwill reuse thatView, filled with the correct data, to be rendered at the screen.The
getView(int pos, View view, ViewGroup parent)method will use the rightViewat 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
ViewHolderjust keeps a pointer to theViewsas obtained byview.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.