How to implement 2 different types of separators (i.e headers) in a ListView Adapter class
The method getViewType
should return 3 (List Item + Separator + Gray Separator). Hence set TYPE_MAX_COUNT
to 3.
private static final int TYPE_GRAY_SEPARATOR = 2;
private static final int TYPE_MAX_COUNT = TYPE_GRAY_SEPARATOR + 1;
Data structure to hold gray separator positions:
private TreeSet<Integer> mGraySeparatorsSet = new TreeSet<Integer>();
Method to add the gray separator.
public void addGraySeparatorItem(ContentWrapper value) {
mData.add(value);
// save separator position
mGraySeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
The method getItemViewType
should return appropriate view based on position.
@Override
public int getItemViewType(int position) {
int viewType = TYPE_ITEM;
if(mSeparatorSet.contains(position))
viewType = TYPE_SEPARATOR;
else if(mGraySeparatorSet.contains(position)) {
viewType = TYPE_GRAY_SEPARATOR;
}
return viewType;
}
The method getView
should handle TYPE_GRAY_SEPARATOR:
public View getView(final int position, View convertView, ViewGroup parent) {
// Existing code
switch(type) {
// Existing cases
case TYPE_GRAY_SEPARATOR:
// Inflate appropriate view
break;
}
// Existing code
}