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.

Android Material UI Template 8 in 1 CodeCanyon
  1. 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);

 

App developer with an eye for design. Loves to create apps with good UI/ UX that doesn’t annoy people. In his spare time, he likes to draw and paint.
Subscribe to stay updated
You'll be first to know about new articles and more. They're sent straight to your inbox!
No Spam, no BS. Promise. You can unsubscribe anytime.

Suleiman

App developer with an eye for design. Loves to create apps with good UI/ UX that doesn't annoy people. In his spare time, he likes to draw and paint.

You may also like...

  • 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.

Subscribe to stay updated
You'll be first to know about new articles and more. They're sent straight to your inbox!
No Spam, no BS. Promise. You can unsubscribe anytime.
Gradle setup, ProGuard rules, Material Design palette, metrics and much more

FREE Material Design Starter Project

For more details, click on the below link.
GET IT NOW FOR ANDROID STUDIO!
Download FREE
STARTER PROJECT
Material Design Template Project for Android Studio
DOWNLOAD STARTER PROJECT
Android O is finally here!
Ready your Apps to get an advantage on Play Store.