Android ViewHolder Pattern Example

Published by - @ninjazhai on September 10, 2013
LIKE and SHARE:

Now we are going to code the smooth scrolling of our Android ListView. In the previous post, we tried to understand how the ListView with adapter works. This time, it will be all about performance.
I did this a separate post because Android ListView is difficult to understand at times. What I have in mind is, “we have to do the basics first, and then apply the optimization.”

android-ViewHolder-pattern-example

What’s with the ViewHolder pattern?

The ViewHolder design pattern enables you to access each list item view without the need for the look up, saving valuable processor cycles. Specifically, it avoids frequent call of findViewById() during ListView scrolling, and that will make it smooth.

Without the ViewHolder Design Pattern

Okay, let’s dig it out and see how it works without the ViewHolder pattern.

Let’s take a look at our previous getView() method in ArrayAdapterItem.java

1. The first time it was loaded, convertView is null. We’ll have to inflate our list item layout and find the TextView via findViewById().

2. The second time it was loaded, convertView is not null, good! We don’t have to inflate it again. But we’ll use findViewById() again.

3. The following times it was loaded, convertView is definitely not null. But findViewById() is constantly called, it will work but, it slows down the performance especially if you have lots of items and Views in your ListView.

With the ViewHolder Design Pattern

Now let’s see how it works with the ViewHolder pattern.
1. The first time it was loaded, convertView is null. We’ll have to inflate our list item layout, instantiate the ViewHolder, find the TextView via findViewById() and assign it to the ViewHolder, and set the ViewHolder as tag of convertView.

2. The second time it was loaded, convertView is not null, good! We don’t have to inflate it again. And here’s the sweet thing, we won’t have to call findViewById() since we can now access the TextView via its ViewHolder.

3. The following time it was loaded, convertView is definitely not null. The findViewById() is never called again, and that makes our smooth ListView scrolling.

Let’s Code!

So here it is, we’ll make use of the Android ViewHolder pattern in our ListView (in just 3 steps!).
Step 1: Add the following static class on our ArrayAdapterItem.java file

// our ViewHolder.
// caches our TextView
static class ViewHolderItem {
    TextView textViewItem;
}

Step 2: Our getView() will now look like this:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolderItem viewHolder;
    
    
      // The convertView argument is essentially a "ScrapView" as described is Lucas post 
      // http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
      // It will have a non-null value when ListView is asking you recycle the row layout. 
      // So, when convertView is not null, you should simply update its contents instead of inflating a new row    layout.
     
    if(convertView==null){
        
        // inflate the layout
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        convertView = inflater.inflate(layoutResourceId, parent, false);
        
        // well set up the ViewHolder
        viewHolder = new ViewHolderItem();
        viewHolder.textViewItem = (TextView) convertView.findViewById(R.id.textViewItem);
        
        // store the holder with the view.
        convertView.setTag(viewHolder);
        
    }else{
        // we've just avoided calling findViewById() on resource everytime
        // just use the viewHolder
        viewHolder = (ViewHolderItem) convertView.getTag();
    }
    
    // object item based on the position
    ObjectItem objectItem = data[position];
    
    // assign values if the object is not null
    if(objectItem != null) {
        // get the TextView from the ViewHolder and then set the text (item name) and tag (item ID) values
        viewHolder.textViewItem.setText(objectItem.itemName);
        viewHolder.textViewItem.setTag(objectItem.itemId);
    }
    
    return convertView;
    
}

Step 3: For the sake of testing, we’re going to put thousands of items in our ListView. On our MainActivity.java, our showPopUp() will now look like this:

public void showPopUp(){
    
    // we'll specify the number of items we want our ListView to have.
    int numberOfItems = 1000;
    
    // add your items, this can be done programatically
    // your items can be from a database
    ObjectItem[] ObjectItemData = new ObjectItem[numberOfItems];
    
    // we'll use a for loop 
    // created objects = number of items specified above
    for(int x=0; x<numberOfItems; x++){
        
        int sampleId = 90 + x;
        ObjectItemData[x] = new ObjectItem(sampleId, "Store # " + (x+1));
        
    }
    
    // our adapter instance
    ArrayAdapterItem adapter = new ArrayAdapterItem(this, R.layout.list_view_row_item, ObjectItemData);
    
    // create a new ListView, set the adapter and item click listener
    ListView listViewItems = new ListView(this);
    listViewItems.setAdapter(adapter);
    listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem());
    
    // put the ListView in the pop up
    alertDialogStores = new AlertDialog.Builder(MainActivity.this)
        .setView(listViewItems)
        .setTitle("Stores")
        .show();
    
}

I tested this code with as much as 2,000 items, and the performance is still smooth and great.

What’s Next?

If you have other ideas regarding this topic, please drop it in the comment section below. I’m more than willing to update this post and improve the life of mankind.

In the next post, we’ll try to use the AsyncTask to load image into the ListView. Something like how the Google Play Store app does it.

Thanks for reading this Android ViewHolder Pattern Example!

The Code of a Ninja Resources