Android: xml layout for a listview with different items

You need to override getViewItemType and getViewTypeCount. You will also need to have custom layouts.

getItemViewType(int position) – returns information which layout type you should use based on position.

You should have a look at the video in the link.

http://www.youtube.com/watch?v=wDBM6wVEO70

private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;
private static final int TYPE_ITEM3 = 2; 

Then

int type;
@Override
public int getItemViewType(int position) {

    if (position== 0){
        type = TYPE_ITEM1;
    } else if  (position == 1){
        type = TYPE_ITEM2;
    }
    else
    {
         type= TYPE_ITEM3 ;
    }
    return type;
}

 @Override
 public int getViewTypeCount() {
        return 3; 
 }
@Override  
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = null;
int type = getItemViewType(position);
  // instead of if else you can use a case
   if (row  == null) {
    if (type == FIRST_TYPE) {
            //infalte layout of type1
      }
    if (type == SECOND_TYPE) {
            //infalte layout of type2
    }  else {
            //infalte layout of normaltype
 }
} 

Leave a Comment