In the previous post, we discussed adding proper support for data set changes and targeted scrolling. In this installment of the series, we will focus on properly supporting animations in your fancy new LayoutManager.In case you’ve forgotten, the code samples are on GitHub.
The Problem With Free
We talked about notifyDataSetChanged() the last time, but you may have noticed that changing the data in this way doesn’t animate the change**. RecyclerView includes a new API for making animated changes, which requires you to notify the adapter which positions in the adapter have changed, and what the action was:
notifyItemInserted()
and notifyItemRangeInserted()
: Insertion of new item(s) at the given position(s).
notifyItemChanged()
and notifyItemRangeChanged()
: Invalidate he item(s) at the given position(s), nothing structural has changed in the data set.
notifyItemRemoved()
and notifyItemRangeRemoved()
: Removal of the item(s) at the given position(s).
notifyItemMoved()
: An item has relocated to a new position in the data set.
By default, your LayoutManager will get “simple item animations” for free when these methods are used. These animations are simply based on whether each current view position is still present in the layout after a change. New views are faded in, removed views are faded out, and other views are moved to their new location. Here’s what our grid layout looks like with the free animations: