You can download the project I am using in this video by clicking here.
Or you can see the source code for the files used in the project here.
ItemTouchHelper
Adding Swipe/Slide
In the MainActivity where the RecyclerView is, create a new ItemTouchHelper object inside the onCreate() method. Then pass in a new Callback object.
helper.attachToRecyclerView(recyclerView);
Replace 0 with makeMovementFlags() in getMovementFlags().
return makeMovementFlags(0, );
To allow swiping from the left, pass ItemTouchHelper.END in the second argument.
If we run the app, we will be able to swipe from left to right. If we try to swipe from right to left, nothing happens.
Muti-Direction Support
To allow multiple directions, separate each direction with the pipe symbol.
ItemTouchHelper.END |
Enable right to left movement by passing in START.
ItemTouchHelper.END | ItemTouchHelper.START
Restart the app and we’ll be able to swipe from both directions.
Enable Dragging
If we run the app now, we will be able to drag the items up and down. Press and hold on the item for a second and you’ll be able to move the item
Removing Item on Swipe
If we run the app, and swipe from the right, the item will be removed from the view.
Swapping Items with Drag
To get the index, grab the viewHolder object from the parameter and call getAdapterPosition().
int draggedItemIndex = viewHolder.getAdapterPosition();
int targetIndex = target.getAdapterPosition();
Collections.swap(recyclerViewItems, draggedItemIndex, targetIndex);
Lastly, call notifyItemMoved() from the adapter and pass in the position of the current item followed by the position of the target.
adapter.notifyItemMoved(draggedItemIndex, targetIndex);
If we run the app, we’ll be able to move the items around.
That is all for this video. If you find this helpful, give it a like, share, and subscribe.