Math is Hard
Math is Hard

Reputation: 942

Android adapter getItemViewType not working properly

I want the first item of a list to be a picture and the subsequent ones to be comments for it. Obviously both types of items have different layouts. My getItemViewType is as follows:

@Override
public int getItemViewType(int position) {
    if (position == 0) {
        return 1;
    } else {
        return 2;
    }
}

And my getView is

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (position == 0) {
        if (convertView == null) {
            ...
        }
    }
    else {
        if (convertView == null) {
            ....
            convertView.setTag(tag);
        }
        Holder holder = convertView.getTag();
        ...
    }
    return convertView;
}

The problem is the recycled views still use the convertView from the one inflated at position 0 for the ones on the comments! Since I don't set tags for that convertView, holder is null. Is there something I'm doing wrong? Note I use an ArrayAdapter if that matters.

Upvotes: 0

Views: 2041

Answers (3)

Konstantin Burov
Konstantin Burov

Reputation: 69228

You have to override getViewTypeCount and return number of different view type that you have:

@Override
public int getViewTypeCount() {
    return 2;
}

Upvotes: 3

MeetTitan
MeetTitan

Reputation: 3568

Try

else {
    if (convertView == null || getViewType(position) == 2)

Upvotes: 0

Adem
Adem

Reputation: 9429

you should not check position.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (getItemViewType(position) == 0) {
        if (convertView == null) {
            ...
        }
    }
    else {
        if (convertView == null) {
            ....
            convertView.setTag(tag);
        }
        Holder holder = convertView.get(tag);
        ...
    }
    return convertView;
}

Upvotes: 0

Related Questions