Skip to content Skip to sidebar Skip to footer

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 fin

Solution 1:

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.

Solution 2:

So, the way I fix the problem I had is by changing the position into viewHolder.getAdapterPosition()

Cheers!

Solution 3:

I advise you to add notifyItemRangeChanged after insert or remove list inside adapter. This work for my project.

Example in remove item :

public void removeItem (int pos) {        
        simpanList.remove(pos);
        notifyItemRemoved(pos);
        notifyItemRangeChanged(pos, simpanList.size());//add here, this can refresh position cmiiw
    }

Post a Comment for "How To Use Recyclerview.adapter Notifyiteminserted/removed In A Right Way?"