java.lang.IndexOutOfBoundsException:索引5无效,大小为5错误

时间:2017-07-22 09:39:44

标签: android list android-recyclerview

我正在使用recyclerview并希望再添加一个项目到列表大小为5.但是当我return list.size()+1;它给了我错误,说java.lang.IndexOutOfBoundsException: Invalid index 5, size is 5

这是getItemCount

@Override
public int getItemCount() {
    if (list.size() == 0) {
        return list.size();
    }
    else {return list.size() + 1;}
}

onBindViewHolder

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    if (holder.getItemViewType() == AD_TYPE) {
        if (mAd != null) {
            ((AdHolder) holder).bindView(mAd);
        } else if (mAds != null && mAds.isLoaded()) {
            NativeAd mAd = mAds.nextNativeAd();
            ((AdHolder) holder).bindView(mAd);
        } else {
            ((AdHolder) holder).bindView(null);
        }
    } else {

        int index = position;
        if (index == 3) {
            ++index;
        }
        listItem post = list.get(index);
        ((ListViewHolder)holder).bindView(post);
    }
}

2 个答案:

答案 0 :(得分:2)

试试这个

@Override
public int getItemCount() {
    if (list.size() == 0) {
        return list.size();
    }
    else {
           // add here new data in your list like this than return size() of new list.
           list.add("data");
           return list.size();
    }
}

答案 1 :(得分:1)

你的bindview持有者中的

改变了这个

    int index = position;
    if (index == 3) {
        ++index;
    }
    listItem post = list.get(index);
    ((ListViewHolder)holder).bindView(post);

To This:

    listItem post; 
    if (position > 3){ 
        post = list.get(position - 1); 
    } else { 
        post = list.get(position); 
    } 
    ((ListViewHolder)holder).bindView(post);