Building Swiggy Offer Animation on Android
Often, it is not the glorious, mind blowing animations but tiny gestures that make the app amazing and a good user experience. Swiggy App is one of them. In the list of restaurants, there is a small icon that represents discount for each of them. When you scroll through the list, the offer icon rotates. It may not seem like a big animation but it is subtle enough to catch the eye of the user and like it. Let’s see how to build it on android!
Final Result
Code!
To build this animation we’ll use our beloved RecyclerView
as it has a OnScrollListener
. Let’s see how to do this in code.
In the callback onScrolled()
we notify the adapter using a custom method recyclerViewScrolled()
and pass the reference of the view and the amount of vertical scroll.
After the adapter is notified, it is his responsibility to get the view holders for all the items and rotate the image view. Let’s see how can this be done:
Let’s evaluate the function recyclerViewScrolled()
. Here we iterate from 0 to the length of the list to get the position for each item. We use that position to get the viewHolder
instance from recyclerView
and then call rotateOfferView()
function. This function rotates the star imageView
by calling the rotate()
extension function defined as below.
This function takes in the amount of scroll and modifies the rotation
property of the imageView
.
That’s it!
Problem
The animation looks fine but there is a small performance issue. Consider the case when there are around 100 restaurants. In that case, we’ll have to perform rotation for all the 100 list items but the screen can displays around 7–8 items per scroll. So why perform rotation on views that are not even visible?
Solution
We have to find a way to get only the list items that are currently visible on the screen. We can do this using the layoutManager
. In FoodRvAdapter
when we pass the reference to recyclerView
we can get its layoutManager
. It contains some handy methods like findFirstVisibleItemPosition()
and findLastVisibleItemPosition()
. Using this methods, we do not need to iterate over the whole list but only between first and last positions and rotate them. You can checkout the commit here and code below:
Huge shoutout to Emílio José for this suggestion! 👏🏻
You can find the source code in this GitHub repository.
Hope it helped you understand the animation. This may not be the best solution out there, so if you have a better approach do comment down below! I’ll be happy to learn about it!
Cheers !🍻 Happy Learning!