Intro To Android (Workbook 2)

View Holder Pattern

Helps speed up list view rendering and scrolling performance by caching view references and resusing them later.

Example

public class ImageAdapter extends BaseAdapter
{
    // ...
    public View getView( int position, View convertView, ViewGroup parent )
    {
        final ViewHolder holder;

        // If starting from scratch
        if ( convertView == null )
        {
            convertView = View.inflate( context, R.layout.inventory_item, null );
            holder = ViewHolder.createViewHolder( convertView );
            convertView.setTag( holder );
        }
        // Otherwise, recycling
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }

        configureImage( items.get( position ), holder );
        configureTitleAndAmount( items.get( position ), holder );

        return convertView;
    }

    private void configureTitleAndAmount( InventoryItem item,
                                          ViewHolder holder )
    {
        holder.name.setText( item.name );
        holder.amount.setText( "" + item.amount );
    }

    private void configureImage( InventoryItem item, ViewHolder holder )
    {
        holder.image.setImageResource( item.imageId );
    }
}

Using the view holder pattern, when creating the view, you check to see if you've inflated this view before. If it has, then you restore that view instead of reinflating and reconfiguring each view element. If you haven't seen this view before, you'll create it from scratch using ViewHolder.createViewHolder(). Either way, you are setting values for the view elements with the data for the position in the list that you are configuring.

ViewHolder

public static class ViewHolder
{
    public TextView  name;
    public TextView  amount;
    public ImageView image;

    public static ViewHolder createViewHolder( View view )
    {
        ViewHolder viewHolder = new ViewHolder();

        viewHolder.name = (TextView) view.findViewById( R.id.inventory_item_name );
        viewHolder.amount = (TextView) view.findViewById( R.id.inventory_item_amount );
        viewHolder.image = (ImageView) view.findViewById( R.id.inventory_item_image );

        return viewHolder;
    }
}

Resources