Junior — Middle
What methods are implemented for adding and removing elements with animation in RecyclerView?
sobes.tech AI
Answer from AI
To add and remove items with animation in RecyclerView, you typically implement methods in the adapter and use RecyclerView.ItemAnimator.
Main steps:
-
Update data: change the data source (e.g., list of items).
-
Notify the adapter:
- Use
notifyItemInserted(position)to add an item. - Use
notifyItemRemoved(position)to remove an item.
- Use
-
Animation:
RecyclerViewwill automatically apply the add or remove animation if anItemAnimatoris set (by defaultDefaultItemAnimator).
Example of adding an item:
items.add(position, newItem);
adapter.notifyItemInserted(position);
Example of removing an item:
items.remove(position);
adapter.notifyItemRemoved(position);
For custom animations, you can create your own class inheriting from RecyclerView.ItemAnimator and override animation methods.