RecyclerView Animations – Changing Items

RecyclerView is a really useful way of displaying content in list form, particularly when the content is dynamic and / or there are large numbers of items. One thing that can be really useful is that we get some really nice animations for free provided we implement our Adapter correctly. For those that have converted from ListView there is a tendency to follow the same usage patterns when updating the data, but this will not get the best out of RecyclerView. In this short series we’ll take a look at the right way to modify the contents of a RecyclerView.Adapter in order to get these animations for free.

Previously in this series we looked at how, by carefully notifying the base Adapter of the precise changes when we add, remove, or move individual items within the list of data items we can get some nice transition animations for very little effort. But this principle extends even further: We can also get some neat transitions when we actually change data items, as well.

To demonstrate this let’s alter our item layout to include a second, longer text element:

This is positioned below the other elements, but has visibility GONE by default, so as it stands this will render exactly the same as before.

Next we need to alter our Adapter so that the data contain a list of Pair items. The String will be the same as before and specify the text for the first TextView, but the Boolean will dictate whether the second TextView should be visible:

The magic happens in the toggleText() and bind() functions. toggleText() toggles the value of the Boolean, which is the second item of the Pair, and then calls notifyItemChanged(). This triggers a re-bind of the ViewHolder and the bind() method will be called and the visibility of the second TextView will be changed according to the value of the Boolean part of the Pair. But all of this is done after the RecyclerView determines the delta between the two states and animates the transition between the two states. As a result we get this behaviour:

All in all, by layering up the different aspects for selective notification of changes that we’ve covered in this series gives us some really nice smooth transitions animations to our RecyclerView and we haven’t had to touch any animation code!