onCreateViewHolder总是返回-1

时间:2019-06-22 14:02:56

标签: android android-recyclerview

为什么我的onCreateViewHolder位置始终为-1?我似乎无法弄清楚为什么

viewHolder.getAdapterPosition()始终为-1

@NonNull
@Override
public AdapterAllComments.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int a) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.model_rv_allcomments_container, viewGroup, false);


    ViewHolder viewHolder = new ViewHolder(view);



    for(int i = 0; i<mDepth.get(viewHolder.getAdapterPosition()); i++) {
        View divider = LayoutInflater.from(viewHolder.itemView.getContext())
               .inflate(R.layout.groupie_section_item_divider, viewHolder.viewHolderLayout, false);
        viewHolder.viewHolderLayout.addView(divider);

    }



    return viewHolder;
}

错误:

     ava.lang.ArrayIndexOutOfBoundsException: length=10; index=-1
    at java.util.ArrayList.get(ArrayList.java:439)
    at com.example.evan.foodforum2.AdapterAllComments.onCreateViewHolder(AdapterAllComments.java:72)
    at com.example.evan.foodforum2.AdapterAllComments.onCreateViewHolder(AdapterAllComments.java:18)
    at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6794)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5975)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)

1 个答案:

答案 0 :(得分:0)

  

我似乎无法弄清楚为什么viewHolder.getAdapterPosition()始终为-1。

嗯,实际上很简单:

// You are creating a new instance of the `ViewHolder`
ViewHolder viewHolder = new ViewHolder(view);

// and then immediately are calling
viewHolder.getAdapterPosition()

但是此ViewHolder尚未附加任何内容,例如:RecyclerView未使用它,适配器未初始化,因此您收到-1,因为适配器位置为-1

如果要在列表项之间使用分隔符,则应查看DividerItemDecoration