Categories
Studio

RecyclerView Swipe to Delete – Weekly Series (Day5)

Welcome to the day 5 of RecyclerView weekly series. Today we’ll learn how to implement swipe to delete functionality to your app’s RecyclerView (or CardView). We are following SSCCE guidelines to write short, self-contained, correct (compatible) example.

All you need to do is initialize ItemTouchHelper.SimpleCallBack. This callback has two parameters: dragDirs and swipeDirs. We will set dragDirs to 0 (as we are not adding dragging functionality to our code). Our swipeDirs will have two swipe directions (LEFT and RIGHT). You can also add/change to UP and DOWN as per your app needs.

Initialise RecyclerView Adapter:

For a simple usage, we initialized the adapter from RecyclerView.Adapter class. But it’s better to initialize it from the Adapter class we created. i.e. MyAdapter.

Initialising the callback:

ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT)

Swipe direction is based on the above line of code. You can choose to swipe the item to only one side or both side (left-right OR up-down).

In onSwiped function, you’ll remove the item using a new custom function created inside RecyclerView’s Adapter. It’s removeItem(int position). See the code below.

// OnCreate
{
    ...
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) {
            // Item swiped.
            int pos = viewHolder.getAdapterPosition();
            adapter.removeItem(pos);
            datasets.remove(pos);
            adapter.notifyItemRemoved(pos)
        }
    };

    // Attach it to recyclerview
    new ItemTouchHelper(simpleCallback).attachToRecyclerView(recyclerView);
...
}

The removeItem function removes the swiped item from the dataset and notifies the adapter about the removed view at the specified position.

The above code is a simple example of how to add swipe functionality to your app. You can play with this feature to delete an item from a list or database. Full code on Github, for your reference.

Leave a Reply

Your email address will not be published. Required fields are marked *