简体   繁体   中英

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?

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!

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
    }

For future readers, this is what I do when inserting/removing in recyclerview For example, my model class is CarsModel

In my adapter

    ArrayList<CarsModel> carsModel;

In onBindViewHolder

    CardModel model = carsModel.get(position);

When removing data in list using button in holder:

    int position = holder.getAdapterPosition();
    carsModel.remove(position);
    notifyItemRemoved(position);

Then when inserting

    carsModel.add(0, model);
    notifyItemInserted(0);

or insert in last row

    carsModel.add(carsModel.size() - 1 , model);
    notifyItemInserted(carsModel.size()-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM