Swipe ⇆ Drag ⇅ Bind RecyclerView

Chetan Sachdeva
Fueled Engineering
Published in
2 min readAug 4, 2017
Copyright © ShutterStock

Thinking of adding swipe/drag ability to your RecyclerView items without making use of any third-party libraries? Well the good news is that there is a utility ItemTouchHelper.SimpleCallback from support library which provides us out of the box methods to do just that. Data Binding makes it even easier.

In ItemTouchHelper.SimpleCallback, you’ll need to overload the constructor SimpleCallback(int dragDirs, int swipeDirs) and override the following methods:

  • isItemViewSwipeEnabled() / isLongPressDragEnabled()
  • onSwiped() / onMove()

Use SwipeItemTouchHelperCallback / DragItemTouchHelperCallback with listeners to attach it with the RecyclerView.

Sexy Swipe ⇆

1. In your BindingAdapter:

  • Pass ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT as swipeDirs to enable swipe for left/right directions.
  • OnItemSwipeListener.onItemSwiped(int position) is called when we swipe left/right. It contains adapterPosition of the swiped ViewHolder.

2. In your XML, bind as follows:

3. There is no point 3, you’re done! 😎

Dope Drag ⇅

1. In your BindingAdapter:

  • Pass ItemTouchHelper.UP | ItemTouchHelper.DOWN as dragDirs to enable drag for up/down directions.
  • OnItemDragListener.onItemDragged(int indexFrom, int indexTo) is called when we drag up/down. It contains adapterPosition of the dragged ViewHolder and the target ViewHolder.

2. In your XML, bind as follows:

3. You knew this was coming? Well, there is actually a point 3:

Hit the little ❤ on the left if you liked this article. 😜

Github Sample

Reference

--

--