Open In App

How to Use Drag-and-Drop in Android Apps?

Improve
Improve
Like Article
Like
Save
Share
Report

You may utilize the Android drag/drop framework to enable your users to move data with a graphical drag and drop action. This can be from one View in your own program to another, or between your app and another when the multi-window mode is enabled. A drag event class, drag listeners, and auxiliary methods and classes are all included in the framework.

Sample Use Cases for Drag & Drop

  1. Something that helps you drag a pointer on live data to get the color of the object or the thing
  2. In your mobile device’s launcher screen, where every program displays, we may effortlessly drag and drop app icons from one location to another.

Geek Tip: To notify the system that a drag event is being called, your application calls the startDrag() function. This technique also distributes data from one view to another.

Gestures Used in the Full Event

Drag and Drop framework in Android allows you to drag and drop one view to another, i.e. in an Activity, if you have two or more views, you may move the data of one view from one view to the other using the Android drag and drop framework. For example, if your Android activity contains two TextViews, one in one half of the screen and the other in the other, the contents from the first TextView may be dragged and dropped to the other TextView.

  1. Started: You begin by producing a ClipData and a ClipData. The item for the data that is being transferred. Provide metadata that is kept in a ClipDescription object within the ClipData as part of the ClipData object. You might wish to use null instead of a real object for a drag and drop action that does not reflect data transfer.
  2. Continuing: If the drag event listener returns true, the program can initiate the drag event. The drag event is in progress, which means it has begun but has not yet finished. For example, if you wish to drag a TextView called tv1 from position 1 to position 2, the intermediate states between the two are in the continuous state.
  3. Dropped: The dragged item is released within the bounding box of a View. The system sends a drag event with the action type ACTION DROP to the View object’s listener.
  4. Ended: When the user drops the item after dragging it and all the events connected with that drop state are called, the system sends a signal to the application that the drop action is complete and all the needed functions are performed. As a result, the system shows that the drag and drop event has ended.

Events Involving Drag

Refer to the table below to understand all the different events involving drag:

getAction() value

Action Performed

ACTION_DRAG_ENTERED When a drag shadow enters the bounding box of a View object, the drag event listener receives this event action type. When the drag shadow enters the bounding box, the listener receives the first event action type. If the listener wants to receive drag events for this action in the future, it must return a boolean true to the system.
ACTION_DRAG_LOCATION DRAG LOCATION This event action type is received by the drag event listener of a View object when it gets an ACTION DRAG ENTERED event while the drag shadow is still within the bounding box of the View.
ACTION_DRAG_STARTED The drag event listener of a View object receives this event action type immediately after the application runs startDrag() and obtains a drag shadow.
ACTION_DRAG_EXITED This event action type is received by the drag event listener of a View object when it receives an ACTION DRAG ENTERED and at least one ACTION DRAG LOCATION event, and after the user has dragged the drag shadow outside the bounding box of the View.
ACTION_DROP

When the user releases the drag shadow over the View object, the drag event listener on the View object receives this event action type. This action type is only delivered to the listener of a View object if the listener responded true in response to the ACTION DRAG STARTED drag event. If the user releases the drag shadow on a View whose listener is not registered, or if the user releases the drag shadow on anything that is not part of the current layout, this action type is not transmitted.

If the drop is properly processed, the listener is supposed to return boolean true. If not, it should return false.

ACTION_DRAG_ENDED Notifies a View that the drag-and-drop action is complete.

Effects and Shadows in the Drags

The system shows an image that the user drags during a drag-and-drop operation. This graphic depicts the data being pulled in terms of data mobility. The picture illustrates some parts of the drag process for other procedures.

The picture is known as a drag shadow. You build it by declaring methods for a View.DragShadowBuilder object and then pass it to the system when you start a drag with startDrag (). The system uses the callback methods described in View.DragShadowBuilder to obtain a drag shadow as part of its answer to startDrag().

Example

In this example, we will drag and drop a text view within a bounding region from one location to another.

Step #1: First, add the application’s layout File

XML




<?xml version="1.0" encoding="utf-8"?>
<ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <LinearLayout
            android:layout_width="match_parent"
            android:id="@+id/gfgLayout"
            android:orientation="vertical"
            android:layout_height="80dp"
            android:background="#0F9D58 ">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/gfgDrop"
                android:text="GFG | First App "
                android:textSize="16p"
                android:layout_margin="24dp"
                android:textColor="#0F9D58 "/>
    </LinearLayout>
</ConstraintLayout>


Step #2: Working with the Kotlin File

Kotlin




package com.geeksforgeeks.sampleDrag
 
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.defGeeksView.DragEvent
import android.defGeeksView.MotionEvent
import android.defGeeksView.DefGeeksView
import android.defGeeksView.DefGeeksViewGroup
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.activity_main.*
 
class MainActivity: AppCompatActivity(), DefGeeksView.OnTouchListener, DefGeeksView.DragHappeningListener {
    private val TAG = MainActivity::class.java.simpleName
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentDefGeeksView(R.layout.activity_main)
        theDraggers()
    }
    private fun theDraggers() {
        gfgDrop.setOnTouchListener(this)
        geeksforgeeksDefGeeksView.setDragHappeningListener(this)
    }
    override fun dragHappening(defGeeksView:DefGeeksView, dragEvent: DragEvent):Boolean {
        Log.d(TAG, "dragHappening: defGeeksView->$defGeeksView\n DragEvent$dragEvent")
        when (dragEvent.action) {
            DragEvent.ACTION_DRAG_ENDED -> {
                return true
            }
            DragEvent.ACTION_DRAG_EXITED -> {
                return true
            }
            DragEvent.ACTION_DRAG_ENTERED -> {
                return true
            }
            DragEvent.ACTION_DRAG_STARTED -> {
                return true
            }
            DragEvent.ACTION_DROP -> {
                val gfgTextDefGeeksView = dragEvent.localState as DefGeeksView
                val defaultText = gfgTextDefGeeksView.parent as DefGeeksViewGroup
                defaultText.removeDefGeeksView(gfgTextDefGeeksView)
                val container = defGeeksView as LinearLayout
                container.addDefGeeksView(gfgTextDefGeeksView)
                defaultText.removeDefGeeksView(gfgTextDefGeeksView)
                gfgTextDefGeeksView.x = dragEvent.x
                gfgTextDefGeeksView.y = dragEvent.y
                defGeeksView.addDefGeeksView(gfgTextDefGeeksView)
                defGeeksView.setVisibility(DefGeeksView.VISIBLE)
                return true
            }
            DragEvent.ACTION_DRAG_LOCATION -> {
                return true
            }
            else -> return false
        }
    }
    override fun onTouch(defGeeksView:DefGeeksView, motionEvent: MotionEvent):Boolean {
        return if (motionEvent.action === MotionEvent.ACTION_DOWN) {
            val dragShadowBuilder = DefGeeksView.DragShadowBuilder(defGeeksView)
            defGeeksView.startDrag(null, dragShadowBuilder, defGeeksView, 10)
            true
        } else {
            false
        }
    }
}


Java




package com.geeksforgeeks.sampleDrag;
 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
 
public class MainActivity extends AppCompatActivity implements View.OnTouchListener, DefGeeksView.DragHappeningListener {
    private final String TAG = MainActivity.class.getSimpleName();
 
    // override onCreate method to set the layout for the activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        theDraggers();
    }
 
    // theDraggers method sets touch listener and drag happening listener for gfgDrop and geeksforgeeksDefGeeksView.
    private void theDraggers() {
        gfgDrop.setOnTouchListener(this);
        geeksforgeeksDefGeeksView.setDragHappeningListener(this);
    }
 
    // DragHappeningListener's method to handle different actions during drag event
    @Override
    public boolean dragHappening(View defGeeksView, DragEvent dragEvent) {
        Log.d(TAG, "dragHappening: defGeeksView->" + defGeeksView + "\n DragEvent" + dragEvent);
        switch (dragEvent.getAction()) {
            case DragEvent.ACTION_DRAG_ENDED:
                return true;
            case DragEvent.ACTION_DRAG_EXITED:
                return true;
            case DragEvent.ACTION_DRAG_ENTERED:
                return true;
            case DragEvent.ACTION_DRAG_STARTED:
                return true;
            case DragEvent.ACTION_DROP:
                View gfgTextDefGeeksView = (View) dragEvent.getLocalState();
                ViewGroup defaultText = (ViewGroup) gfgTextDefGeeksView.getParent();
                defaultText.removeView(gfgTextDefGeeksView);
                LinearLayout container = (LinearLayout) defGeeksView;
                container.addView(gfgTextDefGeeksView);
                defaultText.removeView(gfgTextDefGeeksView);
                gfgTextDefGeeksView.setX(dragEvent.getX());
                gfgTextDefGeeksView.setY(dragEvent.getY());
                defGeeksView.addView(gfgTextDefGeeksView);
                defGeeksView.setVisibility(View.VISIBLE);
                return true;
            case DragEvent.ACTION_DRAG_LOCATION:
                return true;
            default:
                return false;
        }
    }
 
    // OnTouchListener's method to handle touch events and start drag
    @Override
    public boolean onTouch(View defGeeksView, MotionEvent motionEvent) {
        return (motionEvent.getAction() == MotionEvent.ACTION_DOWN) ?
            (defGeeksView.startDrag(null, new View.DragShadowBuilder(defGeeksView), defGeeksView, 10), true) : false;
    }
}
//This Code is Contributed by chinmaya121221


Conclusion

Devices running Android 7.0 (API level 24) or higher enable multi-window mode, which allows users to drag and drop data from one program to another:

  1. The app that initially had the data is referred to as the source app. It’s here when the slog begins.
  2. The app that receives data is referred to as the target app. It’s the point at which the drag comes to an end.

We learned how to use the drag-and-drop functionality in our Android app in this article. We discovered a slew of events related to the drag event. Finally, we demonstrated the drag-and-drop feature. So, utilizing the aforementioned approach, you may create additional drag-and-drop applications in Android.



Last Updated : 24 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads