I have a list view adapter that uses different types of view rows.
Most of the time it works fine. But when I remove an element from the list it crashes. It sends a convertView of the incorrect type to getView
public View getView(int position, View convertView, ViewGroup patent) ...
But getItemViewType is returning the correct type.
public int getItemViewType(int position)
so I see something that looks like this
give me the type for position 1 -> returns correct type (say 1)
give me a view for position 1 with a content view for the wrong type (say type 2.)
Any ideas?
Try overiding getViewTypeCount()
@Override
public int getViewTypeCount() {
return types;
}
Return the number of types of Views that will be created by getView(int, View, ViewGroup). Each type represents a set of views that can be converted in getView(int, View, ViewGroup).
When implemented right, the ListView guarantees that the view provided as the convertView is from the right Type
/**
* @return A view from the ScrapViews collection. These are unordered.
*/
View getScrapView(int position) {
if (mViewTypeCount == 1) {
return retrieveFromScrap(mCurrentScrap, position);
} else {
int whichScrap = mAdapter.getItemViewType(position);
if (whichScrap >= 0 && whichScrap < mScrapViews.length) {
return retrieveFromScrap(mScrapViews[whichScrap], position);
}
}
return null;
}
You should override getViewTypeCount()
, returning the number of view types you have and override getItemViewType(int position)
returning the view type in the range from 0 to getViewTypeCount() - 1
That's normal, if you get a View
with different type in convertView
, you would create a new View
, and not reuse convertView
.
Probably there are no reusable views with the given type.
Note: This answer is from 2011 and might no longer apply.
I had the same issue and it resulted in crashes or unexpected behavior.
This how I fixed my issue:
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
return mlistItems.get(position).type.ordinal();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListItem item = mListems.get(position);
if (convertView == null) {
switch (item.type) {
case Header:
converview = // Inflate Header Row
break;
case Content:
converview = // Inflate Content Row
break;
}
}
switch (item.type) {
case Header:
//Set header row content
break;
case Content:
//Set content row content
break;
}
return convertView;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With