Animation for drag and swipe items of RecyclerView

Alexey Kuznetsov
3 min readJul 18, 2021
Photo by Rots Marie-Hélène on Unsplash

In this article I show how create smooth animation for RecyclerView item in drag/swipe mode. It’s very simple thing that you can do to improve your application beauty.

If you don’t know how create drag/swipe functional for RecyclerView and first time hear “ItemTouchHelper.Callback”, please check this great tutorial.

Drag & drop animation

I used 4 different animator’s which playing together in AnimatorSet. Below a code for create alpha, scale and custom elevation animator’s. It will be used later inside our realization of ItemTouchHelper.Callback:

For drag action we need two animations: for start, for drop. Start animation you should create inside onSelectedChanged method, because documentation says:

Called when the ViewHolder swiped or dragged by the ItemTouchHelper is changed.

It’s mean we can detect drag start inside this method.

Drop animation should be created inside clearView method, because documentation says:

This is a good place to clear all changes on the View that was done in onSelectedChanged(…), …

As you can see it’s not hard to add some animation for drag action. You may customize it like you want! Add small rotation for example. 😏

Swipe fade animation

Here us need to know offset parameter for change alpha of item CardView. The correct way do it inside onChildDraw method with use of dX value. Documentation says:

If you would like to customize how your View’s respond to user interactions, this is a good place to override.

dX - The amount of horizontal displacement caused by user’s action

In this code we have some variables:

  • targetX - x position where alpha will have corner value;
  • translationX - x position between -targetX and targetX;
  • ratio - x offset conversion to float value which will have values from 0.0 to 1.0;
  • alpha - inverted ratio value (e.g. ratio=0.2, alpha will be 0.8);
  • resultAlpha - final alpha for CardView which will have values from ALPHA_SWIPE_MIN to 1.0.

Small extensions from code above:

And it’s all! I hope it will help somebody!

--

--

Alexey Kuznetsov

Android developer. Creator of Scriptum application for manage notes.