The Android ListView, On of the complex composite widget in Android.So we have to deal with ListView wisely. To populate data onListView we have to use CursorAdapter or ArrayAdapter.Here in this article we use ArrayAdapter.
Inside ArrayAdapter there is method call getView(int position, View convertView, ViewGroup parent).Inside this method data is bound to list item. Typical ArrayAdapter code is added here.
What happen actually.
ListView is designed for scalability and performance. In practice, this essentially means
1.It tries to do view inflation few as possible.
2.Draw list items only that are visible in screen.
Normally ListView use view recycle system with RecyclerListener and ScapViews. What basically there are doing is,When ever the list item going off from screen,It is added to Scrap heap then reused it for the list item that going on screen.
So then what are the issues with above ArrayAdapter.
- View Inflation is done always.
- findViewById is always calling.
View Recycling (Eliminating 1st issue)
When the view recycling start to happen the converterView is not null.So then we can normally use it updating data rather than create it again.
Here we check for null and if it is null, then we inflate it again. Here we reducing view inflation. View inflation is more resource intensive task in Android.
So following source code showing example of optimized ArrayAdapter.
ViewHolder Pattern (Eliminating 2nd issue)
So Above adapter also have performance issue.It always find views using their Id. Finding view by id is also resource intensive task, because findViewById methodrecursively go through view hierarchy to find child view.
To eliminate this problem we use ViewHolder class to hold references for already founded view after inflation is done.Then ViewHolder add as a tag of View. This would guaranteed to findViewById only if inflation happens.
So following source code shows more improved ArrayAdapter.
So you can feel deference when this is implemented.
Here I have attached source code for live example of those three Adapters.You can install it and try to feel deference. ListViewOptimization.zip
There is nice Video from Google engineers about ListView Google I/O 2010 - The world of ListView