Swipe ⇆ Drag ⇅ Bind RecyclerView
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
asswipeDirs
to enable swipe for left/right directions. OnItemSwipeListener.onItemSwiped(int position)
is called when we swipe left/right. It containsadapterPosition
of the swipedViewHolder
.
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
asdragDirs
to enable drag for up/down directions. OnItemDragListener.onItemDragged(int indexFrom, int indexTo)
is called when we drag up/down. It containsadapterPosition
of the draggedViewHolder
and the targetViewHolder
.
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. 😜