Reusing views in Android Listview with 2 different layouts

You need to let the adapter’s view recycler know that there is more than one layout and how to distinguish between the two for each row. Simply override these methods:

@Override
public int getItemViewType(int position) {
    // Define a way to determine which layout to use, here it's just evens and odds.
    return position % 2;
}

@Override
public int getViewTypeCount() {
    return 2; // Count of different layouts
}

Incorporate getItemViewType() inside getView(), like this:

if (convertView == null) {
    // You can move this line into your constructor, the inflater service won't change.
    mInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    if(getItemViewType(position) == 0)
        convertView = mInflater.inflate(R.layout.listview_item_product_complete, parent, false);
    else
        convertView = mInflater.inflate(R.layout.listview_item_product_inprocess, parent, false);
    // etc, etc...

Watch Android’s Romain Guy discuss the view recycler at Google Talks.

Leave a Comment