Drag and drop item of recyclerview in android

Item drag and drop of recyclerview is the very cool feature in android. Drag and drop feature is the inbuilt feature of recyclerview. There are many external libraries are available to drag and drop item and swipe item position. But in this tutorial, I am explaining how to implement this awesome feature of recyclerview which is inbuilt in RecylerView?

Very first thing we need to add the recyclerview dependency in our build.gradle file.

Now you need to add this into layout file.

RecylerView provides ItemThouchhelper class to drag and drop. ItemTouchHelper is the best utility that helps to drag and drop item smoothly. It provides many features like swipe item and restricted target to drop an item, awesome animation and much more. For that recyclerview instance should be attached to ItemTouchHelper callback.

Here I want to drag the recycler view item on long pressed, So I will be enabled isLongPressDragEnabled() and disable the swipe feature isItemViewSwipeEnabled().

Ok Great 🙂 Now I need three different listeners to handle all request. What are the requests?

1. While clicking on a view item image to start to item drag.

2. A clickable item view should be the selectable background color and after dismissed, it should be unselected.

3. While moving the item and item dismissed in a target area update recyclerView adapter.

So these three listeners are required for action. Let me create three listeners first then after we will see how and where we need to implement those?

Now all three listeners are ready. Let’s implement all in our custom adapter class.

With our Callback ready, we can create our ItemTouchHelper and call attachToRecyclerView. Here you need implements the OnStartDrag listener and call the startDrag(viewHolder).

Wrapping up: This is a great implementation of ItemTouchHelper. However, it should be clear that a third-party library is not needed for basic drag & drop and swipe-to-dismiss with RecyclerView. RecyclerVew provides the awesome inbuilt feature to handle all this request. If you wondering Kotlin for android then I would be recommended to check all this post of Kotlin Category.

Here is the source code link for drag and drop item recyclerView in android.

Please do subscribe your email to get every newsletter from this blog and if you feel that this post helps you then do not forget to share and comment below.

You can learn all articles of MobologicPlus from the android app, which is available to download below.

Keep Happy coding 🙂

6 thoughts on “Drag and drop item of recyclerview in android

  1. Hi,
    I like your post. But in this post suppose we use number like 1,2,3 and so on instead of image, then if we drag the item , number is not updated.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.