RecyclerView: Swiping with style ;-)

Implementing swipe to dismiss pattern on a RecyclerView is quite simple, you just need to add an ItemTouchHelper.SimpleCallback to your RecyclerView, choose swipe directions and do something (maybe remove the item from your data?) on item swiped callback.

But how to add the amazing background/icon stuff just like Gmail and other apps do?

It can be done in many ways, but the most straightforward and less resource consuming one is drawing your background and icon directly on the canvas where the swiped row is being drawn.

So just override the onChildDraw method in your SimpleCallback.

public void onChildDraw (Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,float dX, float dY,int actionState, boolean isCurrentlyActive){
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

As you can see these method already provides a Canvas which you can draw on. You want a background? Just draw it on the canvas like this:

  • create a ColorDrawable
final ColorDrawable background = new ColorDrawable(Color.RED);
  • set drawable bounds using the viewHolder and dX (horizontal displacement) parameters (imagine you’re swiping right)
background.setBounds(0, itemView.getTop(),   itemView.getLeft() + dX, itemView.getBottom());
  • draw your background on canvas

You can do the same with the icon representing the action to be taken (for instance “delete” the row)

Drawable icon = ContextCompat.getDrawable(context, R.drawable.my_icon);
// compute top and left margin to the view bounds
icon.setBounds(viewHolder.itemView.getRight() - iconHorizontalMargin, top, viewHolder.itemView.getRight() - iconHorizontalMargin, top + icon.getIntrinsicHeight());

That’s it!

If you like I’ve packed it all in an android library (RecyclerViewSwipeDecorator) and put it on GitHub:

There you can find getting started directions, library code and a sample app showing off how to use it.