Notify Item Removed Safely
RecyclerView's adapter provides more powerful methods for developers to animate their list like you can easily run a remove animation on one particular item in the list by calling adapter.notifyItemRemoved(position)
.
But you must be careful with the position
when you removed the one last item in your list, for there won't be any item left in your list to be animated, you might just get an java.lang.IndexOutOfBoundsException
instead of an animation.
So in my case, I use adapter.notifyItemRemoved(position)
only when there are items left in my list like:
if (list.size() > 0) {
adapter.notifyItemRemoved(position); // animate removing when there are items left in the list.
} else {
adapter.notifyDataSetChanged(); // refresh the whole list there is no item left in the list.
}