ViewHolder inflating layout on even and odd position

亡梦爱人 提交于 2019-12-01 00:47:54

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!