I have a RecyclerView with Adapter and ViewHolder classes, so it's 3 classes, I've added a onLongClick in my ViewHolder, when it's long clicked, the selected item will be removed, i'm removing it as the following :
MyRV.Items.remove(getLayoutPosition());
MyRV.mAdapter.notifyItemRemoved(getLayoutPosition());
Items :
- Item_1
- Item_2
- Item_3
- Item_4
Item_5
Removing Item 2 - Item 2 removed . Removing Item 3 (which is item 2 now) - Item 1 removed (item - 1) .
My Data items are about 7 items, So here's what's happening. When first remove, it removes the correct item, when you click on remove again, it removed the above item rather than removing the selected item, and when the size is 1, it FC because invalid size .
My question is similar to this : using notifyItemRemoved or notifyDataSetChanged with RecyclerView in Android
But the answers didn't work, none of them, from itemRange to index + 1 .
public class MyAdapterextends RecyclerView.Adapter<MyViewHolder> {
private List<MyItem> itemList;
public Context context;
public MyAdapter(Context context, List<MyItem> itemList) {
this.itemList = itemList;
this.context = context;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.myitem, null);
return new MyViewHolder(layoutView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.From.setText(itemList.get(holder.getAdapterPosition()).getFrom());
holder.To.setText(itemList.get(holder.getAdapterPosition()).getTo());
}
@Override
public int getItemCount() {
return this.itemList.size();
}
}
Activity
LinearLayoutManager LinLayout = new LinearLayoutManager(MyActivity.this, LinearLayoutManager.VERTICAL, false);
mAdapter = new MyAdapter(MyActivity.this, Items);
RcView.setItemAnimator(new ItemAnimator());
RcView.setHasFixedSize(true);
RcView.setLayoutManager(LinLayout);
RcView.setAdapter(mAdapter);