How to use RecyclerView.Adapter notifyItemInserted/Removed in a right way?
Assigning the position to a variable in onBindViewHolder
will lead to an inconsistent state if items in the dataset are inserted or deleted without calling notifyDataSetChanged
.
To use onItemInserted
or onItemRemoved
the data in the viewholder should remain consistent since it will not be redrawn and onClick
would use this invalid position assigned before an item was added or removed.
For this and other use cases the RecyclerView.ViewHolder
provides methods to access its position and id:
Use getAdapterPosition()
or getItemId()
to get valid positions and ids.
Also have a look on the other methods available in RecyclerView.ViewHolder
.
So, the way I fix the problem I had is by changing the position
into viewHolder.getAdapterPosition()
Cheers!