Intro To Android (Workbook 2)

View Holder Pattern

This pattern is used to improve ListView rendering and scrolling performance by caching view references and resusing them later.

Example

In or getView() function, we check to see if we've aready inflated this view before (by using the setTag() function). 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.

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 );
    }
}

ViewHolder

We create a view holder to hold references to inflated views. This is useful because we can reuse or recycle views and update with the data for a newly displayed row item.

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