Creating ViewHolders for ListViews with different item layouts

ListView has a built in type management system. In your adapter, you have several types of items, each with their own view and layout. By overriding getItemViewType to return the data type of a given position, ListView is garunteed to pass in the correct convertview for that type of data. Then, in your getView method simply check the datatype and use a switch statement to handle each type differently.

Each Layout type should have its own viewholder for naming clarity and ease of maintainence. Name the ViewHolders something related to each data type to keep everything straight.

Trying to overlap everything into one ViewHolder is just not worth the effort.

Edit Example

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    int viewType = this.getItemViewType(position);

    switch(viewType)
    {
       case TYPE1:

        Type1Holder holder1; 

         View v = convertView; 
         if (v == null) { 
             LayoutInflater vi = (LayoutInflater)getContext().getSystemService     (Context.LAYOUT_INFLATER_SERVICE); 
             v = vi.inflate(R.layout.layout_mylistlist_item_type_1, parent, false); 

             holder1 = new Type1Holder (); 
             holder1.text = (TextView) v.findViewById(R.id.mylist_itemname); 
             v.setTag(holder1); 
         } 
         else { 
             holder1 = (Type1Holder)v.getTag(); 
         } 

         MyListItem myItem = m_items.get(position); 

         // set up the list item 
         if (myItem != null) { 
             // set item text 
             if (holder1.text != null) { 
                 holder1.text.setText(myItem.getItemName()); 
             } 
         } 

         // return the created view 
         return v; 


     case TYPE2:
            Type2Holder holder2; 

         View v = convertView; 
         if (v == null) { 
             LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
             v = vi.inflate(R.layout.layout_mylistlist_item_type_2, parent, false); 

             holder2 = new Type2Holder (); 
             holder2.text = (TextView) v.findViewById(R.id.mylist_itemname); 
             holder2.icon = (ImageView) v.findViewById(R.id.mylist_itemicon); 
             v.setTag(holder1); 
         } 
         else { 
             holder2 = (Type2Holder)v.getTag(); 
         } 

         MyListItem myItem = m_items.get(position); 

         // set up the list item 
         if (myItem != null) { 
             // set item text 
             if (holder2.text != null) { 
                 holder2.text.setText(myItem.getItemName()); 
             } 

             if(holder2.icon != null)
                 holder2.icon.setDrawable(R.drawable.icon1);
         } 


         // return the created view 
         return v; 


       default:
           //Throw exception, unknown data type
    }
}