You need to override the following methods:
https://developer.android.com/reference/android/widget/Adapter.html#getViewTypeCount()
https://developer.android.com/reference/android/widget/Adapter.html#getItemViewType(int)
These will let the listview know how many types of views you have and which position is of which type. This will prevent the listview from passing the incorrect convertview type into your getView method.
EDIT:
Let's take a step back. The reason you are seeing this problem is ListView is passing the incorrect convertView into your getView() method. The default getViewTypeCount() returns 1, so listView assumes you only have one view type. You are using two types of views for your rows: R.layout.list_offer_group, and R.layout.list_offer. When convertView is not null, you are not checking to see which layout convertView is -- in some cases it will be the incorrect layout.
To remedy this:
override getViewTypeCount to return 2, since you have two different types. Override getItemViewType to use your group/non-group logic
public int getItemViewType(int position) {
if (nameCompare.equalsIgnoreCase(offers[position].getCustomerName())) {
return 0;
} else {
return 1;
}
}
This is now returning 0 for groups and 1 for non-groups. Then we can use getItemViewType() in getView to determine which view we are using, so:
if (nameCompare.equalsIgnoreCase(offers[position].getCustomerName())) {
convertView = inflater.inflate(R.layout.list_offer_group, null);
}
else {
nameCompare = offers[position].getCustomerName();
convertView = inflater.inflate(R.layout.list_offer, null);
}
becomes:
if (getItemViewType(position) == 0) {
convertView = inflater.inflate(R.layout.list_offer_group, null);
}
else {
nameCompare = offers[position].getCustomerName();
convertView = inflater.inflate(R.layout.list_offer, null);
}
This should fix your behavior since now ListView knows you have 2 view types (getViewTypeCount) and which rows in your list are of which type (getItemViewType). It will no longer pass a convertView of type group into a getView call for a row of type non-group and vice versa.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…