ViewHolder inflating layout on even and odd position

前端 未结 1 1325
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 07:02

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

相关标签:
1条回答
  • 2021-01-07 08:03

    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;
    }
    
    0 讨论(0)
提交回复
热议问题