androidandroid-recyclerview

How to use RecyclerView.Adapter notifyItemInserted/Removed in a right way?


For instance, you have an adapter and in onBindViewHolder method you set OnClickListener to some views (and do some actions there depending on view position). You should assign final to position param of method onBindViewHolder so it could be accessible from onClick().

After changing dataset (remove or add item in list) you call onItemInserted or onItemRemoved and this really adds/removes a view in the recyclerview, BUT it does not refresh other viewitems so when you click on a neighbor viewitem it will open a screen or show data with invalid index. To avoid this I basically call notifyDatasetChanged to call onBind to all visible views and remove/add some views.

So how to refresh other views when you call notifyItemInserted/removed or how to work with these methots appropriately?


Solution

  • 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.