Making RecyclerView Items Swipeable

Updated 5 March 2017

Save

Working with recycler view is pretty easy and has made android programming a bit easy, but then also you need to know how exactly to use this powerful tool as per your wish.

To make items of a recycler view swipeable in any direction the google developers had provided you the a utility called the ItemTouchHelper which itself extends RecyclerView.ItemDecoration Class, so this can be applied to any recycler view and exactly in your activity where you set the adapter of your recycler view or any where in your activity and not in the adapter class of your recycler view.

With the introduction of this utility making the views of the recycler view swipeable has become very easy.  In order to use this utility you first need to create a callback to this utility itself in which you need to override two basic methods of the callback class (namely onMove and onSwiped) plus another method (namely onChildDraw) if you wish to draw any child (or say paint the background to red) when any item is swiped.

Lets now have a look at the code  :

Explanation : this piece of code allows you to add a callback if your item is swiped in the left direction.

  1. onMove :  this method allows you to move the whole item from one position to another in the adapter. I didn’t wanted this feature so i returned false here. Feel free to implement this method with your logic.
  2. onSwiped : this method is called when your item is swiped , i just wanted to remove the item when it is left swiped so i just checked the direction first then called the remove item of the adapter i created (this method just removes the item from the list associated with adapter and notifies the adapter that the item range has changed).
  3. onChildDraw : overriding this method is entirely optional and as per your UI design . I wanted to notify the user with a red background color so that it becomes quite understandable to the user that something is going to happen if he still swipes to the left.

With this being done you are all set to go, now you just have to attach this callback to a new ItemTouchHelper class object and associate this object with your recycler view and this is very easy .

Code to attach with recycler view :

And all is done,  build your project and see how it looks 🙂

Keep coding and keep sharing 🙂

author
. . .

Leave a Comment

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


2 comments

  • Android Rion
    • anchit (Moderator)
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home