Android ListView view holder pattern

When using a ListView in Android you should always use the view holder pattern in your adapter class to improve the performance of scrolling the ListView. The view holder design pattern allows you to access each view of the ListView without having to get a reference to the view objects each time. Without this pattern you would use findViewById to get the reference for each view for every ListView item as it is scrolled.

I’ll start with the code for a simple ListView adapter using a ViewHolder class, then I’ll explain what’s happening.

This adapter extends android.widget.BaseAdapter, it overrides four methods of that class, and implements a constructor. The constructor takes a java.util.List of MenuItem objects as one of its parameters, this is the list of objects to be displayed in the ListView, where MenuItem is simply a class consisting of a String that holds the display text for a menu item.

At the bottom of the adapter class is a nested class called ViewHolder, this is what provides the view holder pattern. In here you declare all the View items that are in the layout file of your ListView items, in this case just one TextView.

All the magic of the ViewHolder happens in the overridden getView method. First we check if the view parameter is null, i.e. this is a new item in the ListView. If it is null we inflate the layout for the list item, instantiate a new ViewHolder, then call findViewById on all the views in the layout file and assign them to the ViewHolder members. Finally we set the new ViewHolder object to be the tag for the view parameter (on line 35). If the view parameter is not null, i.e. this view has already been inflated and is being re-used, we just get hold of the ViewHolder object from the tag of the view (line 38).

Now we have a ViewHolder object we can assign the values from the object we are displaying (the MenuItem in this case) to the views we have previously assigned to the ViewHolder (using findViewById). In this example we are just doing a setText on the TextView to the menuText property of the MenuItem, but usually there would be more views such as images and text which you will set the values for.

What all this means is that you only have to do the slow findViewById on the views the first time the layout is inflated, after that if the view is being re-used you already have a reference to the views and so the ListView scrolling will be much quicker and smoother.

Right, got to get off to my day job now. The reason I’m up early writing this is because I couldn’t sleep from the excitement of the new RouteMaster bus being introduced on route 137 this morning – you guessed it, that’s the bus I use to get to work! It’s a game changer.

Leave a Reply

Your email address will not be published. Required fields are marked *