问题
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