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

大兔子大兔子 提交于 2019-12-21 05:06:11

问题


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?


回答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.




回答2:


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

Cheers!




回答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
    }


来源:https://stackoverflow.com/questions/35812485/how-to-use-recyclerview-adapter-notifyiteminserted-removed-in-a-right-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!