{"id":82233,"date":"2021-07-16T09:00:41","date_gmt":"2021-07-16T03:30:41","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=82233"},"modified":"2024-08-03T14:40:33","modified_gmt":"2024-08-03T09:10:33","slug":"android-drag-drop","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/","title":{"rendered":"Drag and Drop in Android"},"content":{"rendered":"<p>In this article, we will go ahead with Android Drag and Drop feature. Android Drag and Drop feature allows you to drag a piece of information or data from one view to another view.<\/p>\n<p>You must have seen apps like a gallery or To-Do list. In those apps, you get a feature to reorder your content. You can reorder the task with higher priority at the top. You can shift your completed job to another view and leave the unaccomplished tasks in the same view.<\/p>\n<p>These all things are possible because of the Drag and Drop feature. In this article, we will try to understand each aspect of Android Drag and Drop in detail.<\/p>\n<h3>Android Drag and Drop<\/h3>\n<p>Whenever we make a gesture of dragging over the data, then the drag event listener gets triggered. It prompts the application that a drag event has started. Corresponding to this drag event, we have a drag callback method. This drag callback method specifies the task.<\/p>\n<p>Corresponding to this drag event, we have a drag callback method that specifies the tasks to be performed during the drag action. This method enables the application to manage the data being dragged and determine the appropriate actions.<\/p>\n<p>When the dragging gesture stops, the drag event concludes, leading to the drop event. The drop event finalizes the action, specifying where the dragged data should be placed.<\/p>\n<h3>Features of Drag and Drop in Android<\/h3>\n<p>Let\u2019s list out few features of Android Drag and Drop:<\/p>\n<p><strong>1. Transfer Data:<\/strong> Using the Drag and drop feature, you can move information or data from one view to another. This is useful in applications where you need to organize or reassign data dynamically, such as transferring files between folders.<\/p>\n<p><strong>2. Reorder List:<\/strong> You can reorder a given list according to your needs. This is particularly helpful in applications like task managers or to-do lists, where you need to prioritize tasks by dragging them to different positions within the list.<\/p>\n<p><strong>3. Easy Deleting:<\/strong> You can delete items from a list using the drag and drop events. Simply drag an item to a designated delete area or trash icon to remove it from the list, enhancing the user experience by making deletion intuitive and straightforward.<\/p>\n<p><strong>4. Building Applications:<\/strong> You can build colour mixing applications where users drag colors to a mixing area to create new colors. This feature can be used in creative applications, allowing users to interactively blend and experiment with different hues.<\/p>\n<p><strong>5. Building Games:<\/strong> You can event-build games using the drag and drop feature. For example, puzzle games where pieces need to be dragged to specific locations or interactive educational games where objects are matched or sorted by dragging.<\/p>\n<h3>Components of Android Drag and Drop<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Components-of-Android-Drag-and-Drop.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82787\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Components-of-Android-Drag-and-Drop.jpg\" alt=\"Components of Android Drag and Drop\" width=\"840\" height=\"484\" \/><\/a><\/p>\n<p>Three main components are used to implement the Android Drag and Drop feature in your android project. Those three components are as follows:<\/p>\n<ul>\n<li>Drag Event Class<\/li>\n<li>Drag Listeners<\/li>\n<li>Helper Methods<\/li>\n<\/ul>\n<p>Let\u2019s see each of them in detail.<\/p>\n<h4>1. Android Drag Event Class<\/h4>\n<p>The Drag Event Class is responsible for handling all such drag actions. This class provides essential methods, objects, and constants needed to support and control the dragging process. For instance, it offers callbacks that respond to different phases of the drag event, such as when the drag starts, during the drag, and when the drag ends. By leveraging these features, developers can create interactive and responsive drag-and-drop experiences within their applications.<\/p>\n<h4>2. Android Drag Listeners<\/h4>\n<p>Whenever a view encounters a drag event, it either calls the onDragEvent() callback method or implements the View.onDragListener() method. While calling the listener, the application passes the DragEvent object.<\/p>\n<p>The UI elements or views you have defined in your layout can either have a listener or callback method or even both.<br \/>\nThese listeners help the application respond to all drag events, and the callback method consists of the function that is supposed to perform.<\/p>\n<h4>3. Android Helper Methods<\/h4>\n<p>The helper methods help us to implement various functionalities with the drag and drop event. For example, suppose you need to transfer the information of the route along with the data. In other words, if you wish to show the source and destination for data that was dragged.<\/p>\n<p>The data which moves need to have two things:<\/p>\n<ul>\n<li>ClipData, and<\/li>\n<li>ClipData.Item<\/li>\n<\/ul>\n<p>The description of the data(or metadata) is stored in the Clip Description object. The clip description object resides in the Clip Data. If you don\u2019t want to pass any description and the data, you can leave the field as NULL.<\/p>\n<p>In some scenarios, you may be required to show a shadow of the dragged path. It helps to identify that here the data was moved on. For this case, you can use the DragShadowBuilder on your view element.<\/p>\n<h3>Stages of Android Drag and Drop<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Stages-of-Android-Drag-and-Drop.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82788\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Stages-of-Android-Drag-and-Drop.jpg\" alt=\"Stages of Android Drag and Drop\" width=\"583\" height=\"565\" \/><\/a><\/p>\n<p>There are generally four stages through which any Drag and Drop feature in Android goes through. Let\u2019s see each of them in detail.<\/p>\n<h4>1. Started<\/h4>\n<p>Whenever the user tries to drag some element from one view to another, the first method is startDrag(). The startDrag() method is triggered as soon as the user starts dragging. It takes three parameters whenever invoked.<br \/>\nThose three parameters are the actual data, its metadata, and the callback method.<\/p>\n<p>To get the hang of the path through which the data is travelling, the application creates a drag shadow.<\/p>\n<p>After the startDrag() event has been invoked, then the drag event listener is triggered. It indicates that a drag event has occurred recently. The system uses the ACTION_DRAG_STARTED to signal that the process has started. If the system wants to receive other drag events, then it needs to return from the drag event listener; otherwise false.<\/p>\n<h4>2. Continuing<\/h4>\n<p>The continuing state is achieved after the event listener returns true, indicating that the drag operation is still ongoing. During this phase, you have the opportunity to provide visual feedback by altering the appearance of the view. For example, you might highlight the drop target or change the cursor to give users a clear indication of where they are dragging the data. This helps improve user experience by making the interaction more intuitive and visually engaging.<\/p>\n<h4>3. Dropped<\/h4>\n<p>The dropped state is achieved as soon as the user drops the data item he was dragging. In such scenarios, the listener linked to the view receives an action as ACTION_DROP.<\/p>\n<p>Here the point which you should keep in mind is as follows. If the user drops the data in the target view(the view registered to receive the data), only the ACTION_DROP works. Otherwise, the data resides in the root view itself.<\/p>\n<h4>4. Ended<\/h4>\n<p>The ended state is reached once the drag operation is complete, either after the data has been dropped or if the drag is canceled. The event listener receives an ACTION_DRAG_ENDED action, indicating the conclusion of the drag event.The point to note is that the ACTION_DRAG_ENDED works even if the data does not release in the target view.It&#8217;s crucial for performing any final cleanup or updating the state of the application after the drag operation, ensuring that resources are released and the interface reflects the final state of the drag action.<\/p>\n<h3>Drag Event actions<\/h3>\n<p>To handle the states of the Drag event, the system applies some actions to the drag event object. Six different actions are sent to the drag event object. Each action behaves as a constant and has an integral value in them.<\/p>\n<table>\n<tbody>\n<tr>\n<td><strong>Action<\/strong><\/td>\n<td><strong>Description\u00a0<\/strong><\/td>\n<\/tr>\n<tr>\n<td><\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">ACTION_DRAG_STARTED<\/span><\/td>\n<td><span style=\"font-weight: 400;\">The drag started action indicates the system about the start of a drag and drop process.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">ACTION_DRAG_ENTERED<\/span><\/td>\n<td><span style=\"font-weight: 400;\">The drag entered action indicates that the pointer of the drag has started shifting the data from the boundary of the view.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">ACTION_DRAG_LOCATION<\/span><\/td>\n<td><span style=\"font-weight: 400;\">It indicates the current position of the data item within the boundary of the view.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">ACTION_DRAG_EXITED<\/span><\/td>\n<td><span style=\"font-weight: 400;\">The drag indicates that the data item has moved out of the boundary of the view.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">ACTION_DROP<\/span><\/td>\n<td><span style=\"font-weight: 400;\">The drop action indicates to the system that the user has released the data item.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">ACTION_DRAG_ENDED<\/span><\/td>\n<td><span style=\"font-weight: 400;\">The drag ended action indicates to the drag event listener that the drag and drop events are completed.\u00a0<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Methods involved in Drag Events<\/h3>\n<p>Several methods are present in the DragEvent class. These methods help us during the drag and drop process. Some of the most commonly used methods are as follows:<\/p>\n<table>\n<tbody>\n<tr>\n<td><strong>Method Name<\/strong><\/td>\n<td><strong>Description<\/strong><\/td>\n<\/tr>\n<tr>\n<td><\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">getAction()<\/span><\/td>\n<td><span style=\"font-weight: 400;\">It returns the integral value of the action that the event is undergoing.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">getClipData()<\/span><\/td>\n<td><span style=\"font-weight: 400;\">It returns the ClipData object that was sent to the startDrag() method.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">getClipDescription()<\/span><\/td>\n<td><span style=\"font-weight: 400;\">It returns the metadata of the data item that is dragged.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">getResult()<\/span><\/td>\n<td><span style=\"font-weight: 400;\">It returns either true or false based on the result of the drag and drop process.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">getX()<\/span><\/td>\n<td><span style=\"font-weight: 400;\">It returns the floating-point value of the x coordinate of the data item.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">getY()<\/span><\/td>\n<td><span style=\"font-weight: 400;\">It returns the floating-point value of the y coordinate of the data item.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400;\">toString()<\/span><\/td>\n<td><span style=\"font-weight: 400;\">It is used to represent the DragEvent object in the form of a string.\u00a0<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Drag Event Listeners and CallBack methods<\/h3>\n<p>A view can listen or respond to drag events by two methods. Those two methods are as follows.<\/p>\n<p><strong>1. Using Listener Methods:<\/strong> For responding to the drag event, the view can implement the onDragListener() method. The onDragListener() method returns true whenever there is a drag event.<\/p>\n<p><strong>2. Using CallBack methods:<\/strong> You can implement the onDragEvent() callback method to respond to drag events.<\/p>\n<p>You can use either of them or even both to respond to the drag events. The application needs to pass the DragEvent object to both methods. Suppose you include both ways at the same time. In such a scenario, the first listener is called, and then the callback method is implemented.<\/p>\n<h3>The Drag Shadow in Android<\/h3>\n<p>Whenever the user shifts data from one view to another, then there is some movement. To describe that movement or to display that path, we use the concept of drag shadow.<\/p>\n<p>The Drag Shadow helps to showcase the path through which the data was dragged. To do so, you can use the DragShadowBuilder class. The class has a few methods and constructors which you can use to implement Drag Shadow.<\/p>\n<h3>Implementation of Android Drag and Drop<\/h3>\n<p>I hope you understood what is meant by drag and drop in Android. Now, it\u2019s time for us to look at how we can implement the learnt concepts through an app.<\/p>\n<p>In this implementation, we will try to build an app with a recycler view, and the items of the recycler view would be draggable. You can drag the items to change their order.<\/p>\n<p>Below are the steps you need to follow to implement the above.<\/p>\n<p><strong>1:<\/strong> Open Android Studio and click on Create New Project.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Drag_Drop_build_1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82789\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Drag_Drop_build_1.png\" alt=\"Android New Project\" width=\"1268\" height=\"876\" \/><\/a><\/p>\n<p><strong>2:<\/strong> Select an Empty Activity and proceed.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Drag_Drop_build_2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82790\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Drag_Drop_build_2.png\" alt=\"Android Activity\" width=\"1308\" height=\"940\" \/><\/a><\/p>\n<p><strong>3:<\/strong> Enter your application name. In my case, it\u2019s \u201cTechVidvanDragDrop.\u201d Next, select Kotlin from the dropdown. For the API level, select API 22 for now.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Drag_Drop_build_3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82791\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Drag_Drop_build_3.png\" alt=\"Android API\" width=\"1452\" height=\"948\" \/><\/a><\/p>\n<p><strong>Step 4:<\/strong> Now, open your app-level Gradle file and add the material dependency for your project.<br \/>\nYou can copy-paste the below code in your Gradle file under the dependencies section.<\/p>\n<h4>Code:<\/h4>\n<p>implementation &#8216;com.google.android.material:material:1.2.1&#8217;<\/p>\n<p><strong>Step 5:<\/strong> Now, you need to create three interfaces in your project. Namely,<\/p>\n<ul>\n<li>ItemDragListener<\/li>\n<li>ItemTouchAdapter<\/li>\n<li>ItemTouchHolder<\/li>\n<\/ul>\n<p>Each of them has its own code, which you may discover below.<\/p>\n<p><strong>Code: ItemDragListener.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.techvidvan.techvidvandragdrop\r\n\r\nimport androidx.recyclerview.widget.RecyclerView\r\n\r\ninterface ItemDragListener\r\n{\r\n    fun onStartDrag(viewHolder: RecyclerView.ViewHolder?)\r\n}\r\n<\/pre>\n<p><strong>The Code for ItemTouchAdapter.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.techvidvan.techvidvandragdrop\r\n\r\ninterface ItemTouchAdapter\r\n{\r\n    fun onItemMove(source:Int, destination:Int):Boolean\r\n    fun onItemRelease(position:Int)\r\n}<\/pre>\n<p><strong>Code: ItemTouchHolder.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.techvidvan.techvidvandragdrop\r\n\r\ninterface ItemTouchHolder\r\n{\r\n    fun onItemSelected()\r\n    fun onItemClear()\r\n}\r\n<\/pre>\n<p><strong>Step 6:<\/strong> Now, you need to create two classes. One is the callback class, and the other is the Adapter Class.<br \/>\nYou can find the codes for both of them below.<\/p>\n<p><strong>Code: ItemTouchcallback.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.techvidvan.techvidvandragdrop\r\n\r\nimport android.graphics.Canvas\r\nimport androidx.recyclerview.widget.GridLayoutManager\r\nimport androidx.recyclerview.widget.ItemTouchHelper\r\nimport androidx.recyclerview.widget.RecyclerView\r\n\r\nclass ItemTouchCallback(private val adapter:ItemTouchAdapter):ItemTouchHelper.Callback()\r\n{\r\n    companion object\r\n    {\r\n        const val FULL = 1.0f\r\n    }\r\n\r\n    override fun isLongPressDragEnabled(): Boolean\r\n    {\r\n        return true\r\n    }\r\n\r\n    override fun isItemViewSwipeEnabled(): Boolean\r\n    {\r\n        return true\r\n    }\r\n    override fun getMovementFlags(\r\n        recyclerView: RecyclerView,\r\n        viewHolder: RecyclerView.ViewHolder\r\n    ): Int\r\n    {\r\n        return if(recyclerView.layoutManager is GridLayoutManager)\r\n        {\r\n            \/\/if the layout is in the form of grid\r\n            \/\/then you can move in all the four directions\r\n            val drag_flags = ItemTouchHelper.UP or ItemTouchHelper.DOWN or\r\n                    ItemTouchHelper.RIGHT or ItemTouchHelper.LEFT\r\n\r\n            val swipe_flags = 0\r\n            \/\/allowing the movements by passing the flags\r\n            makeMovementFlags(drag_flags, swipe_flags)\r\n\r\n        }\r\n        else\r\n        {\r\n            \/\/if the layout is not grid then\r\n            \/\/only two possible directions you can go\r\n            \/\/that is up or down\r\n            val drag_flags = ItemTouchHelper.UP or ItemTouchHelper.DOWN\r\n\r\n            val swipe_flags = ItemTouchHelper.START or ItemTouchHelper.END\r\n            \/\/allowing the movements by passing the flags\r\n            makeMovementFlags(drag_flags, swipe_flags)\r\n        }\r\n    }\r\n\r\n    override fun onMove(\r\n        recyclerView: RecyclerView,\r\n        viewHolder: RecyclerView.ViewHolder,\r\n        target: RecyclerView.ViewHolder\r\n    ): Boolean\r\n    {\r\n        if(viewHolder.itemViewType != target.itemViewType)\r\n        {\r\n            return false\r\n        }\r\n        \/\/providing the source and destination\r\n        \/\/to the adapter\r\n        adapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)\r\n        return true\r\n    }\r\n\r\n    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int)\r\n    {\r\n        \/\/returning the position of the data\r\n        \/\/when its released\r\n        adapter.onItemRelease(viewHolder.adapterPosition)\r\n    }\r\n\r\n    override fun onChildDraw(\r\n        c: Canvas,\r\n        recyclerView: RecyclerView,\r\n        viewHolder: RecyclerView.ViewHolder,\r\n        dX: Float,\r\n        dY: Float,\r\n        actionState: Int,\r\n        isCurrentlyActive: Boolean\r\n    )\r\n    {\r\n        if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE)\r\n        {\r\n            \/\/describing how the view should respond to drag\r\n            val alpha = FULL - Math.abs(dX) \/ viewHolder.itemView.width.toFloat()\r\n            viewHolder.itemView.alpha = alpha\r\n            viewHolder.itemView.translationX = dX\r\n        }\r\n        else\r\n        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)\r\n    }\r\n\r\n    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {\r\n        super.clearView(recyclerView, viewHolder)\r\n        \/\/setting back to original state\r\n        viewHolder.itemView.alpha = FULL\r\n        if(viewHolder is ItemTouchHolder)\r\n        {\r\n            val itemViewHolder = viewHolder as ItemTouchHolder\r\n            itemViewHolder.onItemClear()\r\n        }\r\n    }\r\n\r\n    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int)\r\n    {\r\n        \/\/checking is the movement is there or it is idle\r\n        if(actionState != ItemTouchHelper.ACTION_STATE_IDLE)\r\n        {\r\n            if(viewHolder is ItemTouchHolder)\r\n            {\r\n                val itemViewHolder = viewHolder as ItemTouchHolder\r\n                itemViewHolder.onItemClear()\r\n            }\r\n        }\r\n        super.onSelectedChanged(viewHolder, actionState)\r\n    }\r\n}<\/pre>\n<p><strong>Code: MyRecyclerAdapter.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.techvidvan.techvidvandragdrop\r\n\r\nimport android.annotation.SuppressLint\r\nimport android.content.Context\r\nimport android.view.LayoutInflater\r\nimport android.view.View\r\nimport android.view.ViewGroup\r\nimport android.widget.TextView\r\nimport androidx.cardview.widget.CardView\r\nimport androidx.recyclerview.widget.RecyclerView\r\nimport java.util.*\r\n\r\nclass MyRecyclerAdapter(var context: Context,\r\nvar stringList:MutableList&lt;String?&gt;,\r\nvar listener:ItemDragListener):RecyclerView.Adapter&lt;MyRecyclerAdapter.myViewHolder&gt;(),\r\n    ItemTouchAdapter\r\n{\r\n    inner class myViewHolder(itemView:View):RecyclerView.ViewHolder(itemView)\r\n    {\r\n        \/\/binding our UI components\r\n        var card_view:CardView\r\n        var crd_number:TextView\r\n        var crd_title:TextView\r\n        init {\r\n            card_view = itemView.findViewById(R.id.card_view)\r\n            crd_number = itemView.findViewById(R.id.crd_number)\r\n            crd_title = itemView.findViewById(R.id.crd_title)\r\n        }\r\n\r\n    }\r\n\r\n    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): myViewHolder\r\n    {\r\n        \/\/binding our layout to each item of recycler view\r\n        return myViewHolder(LayoutInflater.from(context).inflate(\r\n            R.layout.each_car_layout, parent, false\r\n        ))\r\n    }\r\n\r\n    @SuppressLint(\"SetTextI18n\")\r\n    override fun onBindViewHolder(holder: myViewHolder, position: Int)\r\n    {\r\n        \/\/setting the title and card number\r\n        holder.crd_title.text = stringList[position]\r\n        holder.crd_number.text = \"\"+(position+1)\r\n\r\n        \/\/if we long click on the card\r\n        \/\/the drag event starts\r\n        holder.card_view.setOnLongClickListener {\r\n            listener.onStartDrag(holder)\r\n            false\r\n        }\r\n\r\n    }\r\n\r\n    override fun getItemCount(): Int\r\n    {\r\n        \/\/returning the size of the list\r\n        return stringList.size;\r\n\r\n    }\r\n\r\n    override fun onItemMove(source: Int, destination: Int):Boolean\r\n    {\r\n        \/\/swapping the items that was just dragged\r\n        \/\/if 1st card was dragged to 3rd card\r\n        \/\/then their positions will change in the list\r\n        Collections.swap(stringList, source, destination)\r\n        notifyItemMoved(source, destination)\r\n        return true\r\n    }\r\n\r\n    override fun onItemRelease(position: Int)\r\n    {\r\n        \/\/removing the item from the list\r\n        stringList.removeAt(position)\r\n        notifyItemRemoved(position)\r\n    }\r\n\r\n}<\/pre>\n<p><strong>Step 7:<\/strong> Now, you need to design your layouts. Go to res &#8212;&gt; layout and select activity_main.xml, and paste the below code.<\/p>\n<p><strong>Code: activity_main.xml<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;LinearLayout\r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:app=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    android:orientation=\"vertical\"\r\n    android:background=\"@color\/black\"\r\n    tools:context=\".MainActivity\"&gt;\r\n\r\n    &lt;TextView\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:text=\"TechVidvan Drag and Drop\"\r\n        android:textColor=\"#FF9800\"\r\n        android:textSize=\"25sp\"\r\n        android:gravity=\"center\"\r\n        android:padding=\"10dp\"\r\n        android:textStyle=\"bold\"\r\n        android:textAllCaps=\"false\"\r\n        \/&gt;\r\n\r\n    &lt;androidx.recyclerview.widget.RecyclerView\r\n        android:id=\"@+id\/recyler_view\"\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\"\r\n        \/&gt;\r\n\r\n&lt;\/LinearLayout&gt;<\/pre>\n<p><strong>Code: each_car_layout.xml<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;androidx.cardview.widget.CardView\r\n    android:id=\"@+id\/card_view\"\r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"wrap_content\"\r\n    xmlns:app=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n    android:background=\"@color\/white\"\r\n    app:cardCornerRadius=\"20dp\"\r\n    android:layout_margin=\"5dp\"&gt;\r\n    &lt;LinearLayout\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:orientation=\"vertical\"\r\n        android:background=\"@color\/white\"\r\n        android:padding=\"5dp\"&gt;\r\n        &lt;TextView\r\n            android:id=\"@+id\/crd_number\"\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            android:text=\"1\"\r\n            android:gravity=\"center\"\r\n            android:textSize=\"30sp\"\r\n            android:textColor=\"@color\/black\"\r\n            android:textStyle=\"bold\"\r\n            android:padding=\"10dp\"\r\n            \/&gt;\r\n        &lt;androidx.cardview.widget.CardView\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            app:cardCornerRadius=\"20dp\"\r\n            android:layout_margin=\"5dp\"&gt;\r\n\r\n            &lt;TextView\r\n                android:id=\"@+id\/crd_title\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:text=\"your_title\"\r\n                android:gravity=\"center\"\r\n                android:layout_gravity=\"center\"\r\n                android:textSize=\"20sp\"\r\n                android:textColor=\"@color\/white\"\r\n                android:padding=\"5dp\"\r\n\r\n                android:background=\"#FF9800\"\r\n                \/&gt;\r\n        &lt;\/androidx.cardview.widget.CardView&gt;\r\n\r\n\r\n    &lt;\/LinearLayout&gt;\r\n\r\n&lt;\/androidx.cardview.widget.CardView&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Step 8:<\/strong> Now, you need to paste the below code in your MainActivity.kt file for the last step.<\/p>\n<p><strong>Code: MainActivity.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.techvidvan.techvidvandragdrop\r\n\r\nimport androidx.appcompat.app.AppCompatActivity\r\nimport android.os.Bundle\r\nimport androidx.recyclerview.widget.GridLayoutManager\r\nimport androidx.recyclerview.widget.ItemTouchHelper\r\nimport androidx.recyclerview.widget.RecyclerView\r\nimport java.util.*\r\nimport kotlin.collections.ArrayList\r\n\r\nclass MainActivity : AppCompatActivity()\r\n{\r\n    lateinit var recycler_view:RecyclerView\r\n    var itemtouchHelper:ItemTouchHelper?=null\r\n    override fun onCreate(savedInstanceState: Bundle?)\r\n    {\r\n        super.onCreate(savedInstanceState)\r\n        setContentView(R.layout.activity_main)\r\n        \/\/Initializing the views\r\n        init()\r\n        \/\/generating the list\r\n        generateList()\r\n    }\r\n\r\n    private fun generateList()\r\n    {\r\n        \/\/adding data to the list\r\n        \/\/that will appear in recycler view\r\n        val my_list:MutableList&lt;String?&gt; = ArrayList()\r\n        my_list.addAll(Arrays.asList(\r\n            \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"\r\n        ))\r\n\r\n        val adapter = MyRecyclerAdapter(this, my_list, object:ItemDragListener{\r\n            override fun onStartDrag(viewHolder: RecyclerView.ViewHolder?) {\r\n                itemtouchHelper!!.startDrag(viewHolder!!)\r\n            }\r\n        } )\r\n        \/\/setting up the adapter to our recycler view\r\n        recycler_view.adapter = adapter\r\n\r\n        \/\/attaching our helper classes to the recycler view\r\n        val callback = ItemTouchCallback(adapter)\r\n        itemtouchHelper = ItemTouchHelper(callback)\r\n        itemtouchHelper!!.attachToRecyclerView(recycler_view)\r\n    }\r\n\r\n    private fun init()\r\n    {\r\n        \/\/binding recycler view to our variable\r\n        recycler_view = findViewById(R.id.recyler_view)\r\n        \/\/fixing the size\r\n        recycler_view.setHasFixedSize(true)\r\n\r\n        \/\/providing grid layout to our recycler view\r\n        val layout_manager = GridLayoutManager(this, 2)\r\n        recycler_view.layoutManager = layout_manager\r\n\r\n    }\r\n}\r\n<\/pre>\n<p>Now after following all the above steps, you are ready to test your ap[plication.<br \/>\nYour application would look as follows:<\/p>\n<p>App Screenshot:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/App_Output_Screenshot.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82792\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/App_Output_Screenshot.jpg\" alt=\"Android Drag and Drop\" width=\"1080\" height=\"2280\" \/><\/a><\/p>\n<h3><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/android-drag-drop-output.gif\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-82807\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/android-drag-drop-output.gif\" alt=\"android drag drop output\" width=\"800\" height=\"1682\" \/><\/a><\/h3>\n<h3>Summary<\/h3>\n<p>Through this article, you understood what drag and drop in android is. You came across its uses and applications. Further in the article, you got to know the several components of the Android Drag and Drop. Moving to the end, you even understood the various stages through which the process goes through. Finally, you saw an implementation of all the concepts by developing an application.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will go ahead with Android Drag and Drop feature. Android Drag and Drop feature allows you to drag a piece of information or data from one view to another view.&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":82784,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2791],"tags":[3790,3791,3792,3793],"class_list":["post-82233","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android","tag-components-of-android-drag-and-drop","tag-drag-and-drop-in-android","tag-features-of-android-drag-and-drop","tag-stages-of-android-drag-and-drop"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Drag and Drop in Android - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn what drag and drop in android is? Learn its uses and applications. See the several components of the Android Drag and Drop.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Drag and Drop in Android - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn what drag and drop in android is? Learn its uses and applications. See the several components of the Android Drag and Drop.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-16T03:30:41+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-03T09:10:33+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/Android-Drag-and-Drop.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Drag and Drop in Android - TechVidvan","description":"Learn what drag and drop in android is? Learn its uses and applications. See the several components of the Android Drag and Drop.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/","og_locale":"en_US","og_type":"article","og_title":"Drag and Drop in Android - TechVidvan","og_description":"Learn what drag and drop in android is? Learn its uses and applications. See the several components of the Android Drag and Drop.","og_url":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-16T03:30:41+00:00","article_modified_time":"2024-08-03T09:10:33+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/Android-Drag-and-Drop.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Drag and Drop in Android","datePublished":"2021-07-16T03:30:41+00:00","dateModified":"2024-08-03T09:10:33+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/"},"wordCount":2065,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/Android-Drag-and-Drop.jpg","keywords":["Components of Android Drag and Drop","Drag and Drop in Android","Features of Android Drag and Drop","Stages of Android Drag and Drop"],"articleSection":["Android Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/","url":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/","name":"Drag and Drop in Android - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/Android-Drag-and-Drop.jpg","datePublished":"2021-07-16T03:30:41+00:00","dateModified":"2024-08-03T09:10:33+00:00","description":"Learn what drag and drop in android is? Learn its uses and applications. See the several components of the Android Drag and Drop.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/Android-Drag-and-Drop.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/Android-Drag-and-Drop.jpg","width":1200,"height":628,"caption":"Android Drag and Drop"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/android-drag-drop\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Drag and Drop in Android"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/82233","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=82233"}],"version-history":[{"count":2,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/82233\/revisions"}],"predecessor-version":[{"id":447573,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/82233\/revisions\/447573"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/82784"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=82233"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=82233"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=82233"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}