Read complete story

Making RecyclerView Items Swipeable

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 🙂

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close