I need two layout to inflate on basis of even and odd position of listview items using ViewHolder. At even position I need a different layout and at Odd position another one
The problem is when the views are recycled, ListView can give you back a "right" layout when you expected a "left" layout. You should override getItemViewType() and getViewTypeCount() in your adapter implementation; these methods ensure that ListView gives you the appropriate view type when it provides a recycled view to getView()
@Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change at runtime
return 2;
}
@Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
@Override
public View getView(int position, View convertView, ViewGroup container) {
int layoutResource; // determined by view type
int viewType = getItemViewType(position);
switch(viewType) {
case 0:
layoutResource = R.layout.list_item_even; break;
case 1:
layoutResource = R.layout.list_item_odd; break;
}
ViewHolder holder;
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, container, false);
holder = new ViewHolder();
...
convertView.setTag(holder);
}
...
return convertView;
}