Android DTT #11 — Adding Animation to RecyclerView is Unbelievably Easy!
RecyclerView is a common component to display a list in Android. It replaces the old and inefficient
ListView and add a lot of flexibility for us to play with. This is usually how I use a
When I want to update the content I just call the
updateItems(List<Data>) method. This is what I will get if there’s a change to the data, in this case adding and removing some items.
It works. Not good, but OK. We can do better.
Adding Animation — setHasStableIds
Did you know that
RecyclerView has default animation for inserting, deleting and changing item position? And it’s pretty easy to get it. You just have to say the adapter that each item on your list has a stable ID, by adding this in the adapter class:
Stable ID means that each data of your item can be represented with an unique ID. Without any modification to your data or activities, here’s the result of that little modification:
So much better. Our apps now looks more alive than ever.
What’s the catch? Your data needs to have an ID of type Long. What to do if that’s not the case? You can use
DiffUtil, which was introduced in Support Library V24.2.0. But it requires a little more code to add and an article of it’s own. Check it in the article below
If you like this, hit that heart button and recommend it to your friends.
ADTT (Android Development Tips and Tricks) is a 31 series of blog posts that I’m trying to finish in throughout May. Click here for index.