Swipe to Dismiss for RecyclerView with ItemTouchHelper
A hidden gem in Android Support Library, is the built in Swipe to Dismiss functionality.
Using the ItemTouchHelper class, we can add this to a RecyclerView.
- Create a SimpleCallback
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { //Remove swiped item from list and notify the RecyclerView } };
The onSwiped() method is where you should remove the item. Don’t forget to notify your RecyclerView!
2. Finally, create an ItemTouchHelper instance and attach it to RecyclerView.
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback); itemTouchHelper.attachToRecyclerView(recyclerView);
Really nice and easy, but what if I want to restore those items again, eg. “undo” swipes via Snackbar for a defined amount of time?
You simply create an instance of your data model and save the item to be deleted.
For eg., in your onSwiped() method, before deleting:
Bean bean = data.get(pos);
Where Bean is your model and data would ideally be List type.
Then, in your Snackbar’s undo listener, you can add ‘bean’ back to your data and update your adapter.
Thanks ! I’ll do it that way!