Swipe to delete

Swipe to delete done easier than you thought

Recently I had to implement swipe to delete function. As is often the case, sometimes you need to enhance the functionality in the application using 3rd party libraries. This is what happened.

It’s nothing wrong with using 3rd party libraries. Here are some advantages that quickly came to my mind:

  • often such code has good quality,
  • you can save some time,
  • in general, reinventing the wheel is not a good idea.

There is also the other side of the coin:

  • open source is cool, but when you find a bug in the library, you need to fix it by yourself,
  • customisation might be cumbersome,
  • you have to accept library’s dependencies, even if you’re not using them,

Last but not least, in my opinion, using a ready-made solution prevents us from discovering and learning new stuff.

It was similar in my case. Ability to delete rows from RecyclerView’s list was all that I needed. A quick look at the documentation and I realised that I could accomplish it very easily!

ItemTouchHelper.SimpleCallback

Using this class, we can detect and react to events related to:

  • swipe items (from right, left or both sides);
  • move items (up, down or both).

Let’s create our implementation based on SimpleCallback (to make code cleaner I placed only the most important fragments, check the full code here):

SimpleCallback’s constructor is using two parameters — which directions you want to support, in our case just swipe from right to left. In onChildDrawmethod, you need to manually calculate and draw the background with an icon (I used ic_delete from the Material icons).

Next thing is to connect Callback with our RecyclerView:

Finally, the last thing you need is ability to delete item in an adapter. You can achieve this by doing that:

Swipe to remove

That’s it! As you can see, the advantages of using 3-rd party libraries overcome some of the drawbacks. You can spend the time saved thanks to using them on researching new ones, and further simplify some tasks.

Links:

Subscribe to our newsletter
Menu