Using the Holder pattern

In our discussion of Android ListViews we showed how to reduce inflation costs by using convertView to recycle our row Views. A further optimization would be to reduce the use of findViewById() by applying the Holder pattern.

Define a static class that holds references to the Views that need to be populated. (Note that static inner classes must be declared in the top level class, which might be either the custom Adapter class itself or the Activity class if it declares the Adapter as an inner class.)

static class ViewHolder {
    TextView label;
    ImageView icon;
}

Android Views can be tagged with any object using the setTag() and getTag() methods. In the getView() method of the Adapter we’ll tag convertView with the holder instance and we’ll retrieve it when we need to repopulate it:

public View getView(int position, View convertView, ViewGroup parent) {
 
    ViewHolder holder;
 
    if (convertView == null) {
        convertView = mInflater.inflate(R.drawable.grid_item, null);
        holder = new ViewHolder();
        holder.icon = (ImageView) convertView.findViewById(R.id.icon);
        holder.label = (TextView) convertView.findViewById(R.id.label);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
 
    holder.label.setText(listItems.get(position).label);
    holder.icon.setImageResource(listItems.get(position).icon);
 
    return convertView;
}

Leave a Reply

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