RecyclerView and IndexOutOfBoundsException: Invalid index #, size is #

泄露秘密 提交于 2019-12-11 11:12:14

问题


I have a simple RecyclerView and I want to remove those items onClick. I was continuously running into a crash depending on when I clicked on certain items in the list with the above error. If you're having similar issues, here's how I solved it:


回答1:


public void onBindViewHolder(final CardViewHolder holder, final int position)

Using position here is useful for some things, but if I used it when removing items from the list, it was causing a crash, instead using:

holder.getAdapterPosition();

resolved my issues immediately.




回答2:


Create a class like this:

public class RecyclerViewNoBugLinearLayoutManager extends LinearLayoutManager {
    public RecyclerViewNoBugLinearLayoutManager(Context context) {
        super( context );
    }

    public RecyclerViewNoBugLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super( context, orientation, reverseLayout );
    }

    public RecyclerViewNoBugLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super( context, attrs, defStyleAttr, defStyleRes );
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
        //try catch一下
            super.onLayoutChildren( recycler, state );
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }

    }
}

When you Init the RecylerView add this:

mRecyclerView = (RecyclerView)findViewById(R.id.list_search);
mRecyclerView.setLayoutManager(new FixRecyclerViewManager(mContext));


来源:https://stackoverflow.com/questions/36730945/recyclerview-and-indexoutofboundsexception-invalid-index-size-is

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