简体   繁体   中英

Deleting last item from RecyclerView does not work

I have a recycler view

A user can delete or add an item in the RecyclerView .

Everything works fine until the RecyclerView reaches 1 element.

When I needed to delete the last item, it does not get deleted. The log shows that the item is removed from the ArrayList , but it still shows in the RecyclerView .

Is something more needed when deleting the last item?

Code:

public void removeItem(int adapterPosition){
       arrayList.remove(adapterPosition);
       Log.. ///
}

When adapterPosition is 0, it does not remove the item.

I have even kept a breakpoint in the method, and it is still showing that the adapterPosition is 0.

You need to call notifyItemRemoved in order to inform the RecyclerView that the item has been removed. This is necessary on every deletion/removal, not just the last one, but it may sometimes appear to work by coincidence if you don't.

That is, your removeItem method (assuming it's on your Adapter ) should look like:

public void removeItem(int adapterPosition){
    arrayList.remove(adapterPosition);
    notifyItemRemoved(adapterPosition);
    Log.. ///
}

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