17 notes &
ListView Optimization on Android
While I have always known about the convertView passed into the getView method, I was only recently made aware of the getViewTypeCount and getItemViewType methods. Both of these allow for better control of view reuse in the getView method.
While the inner workings of the view recycling code is not specified in the official documentation (though you’re welcome to look at the source), it is obvious the both of these methods give some much needed hints to the Adapter.
When subclassing Adapter (or ArrayAdapter, ListAdapter, etc), you should override both methods to provide granular control of view reuse. getViewTypeCount should return the number of distinct view row types while getItemViewType should return a unique integer (in the range 0 to getViewTypeCount() -1 ) representing the type of row view for the row specified.
Secondly, I was completely unaware of the ViewHolder pattern to reduce findViewById calls which are apparently slow. While reading the ListView14 source, I noticed the technique. Basically, you save the references found via findViewById to the different view components into a single object and then attach it to the view via the setTag method. Hrmmm…clever. Checkout the source link to see it in action.
Finally, I stumbled upon this little gem; a talk at Google I/O discussing ListView performance.
Keep those ListViews scrolling like butter!