How to Use Drag-and-Drop in Android Apps?
Last Updated :
24 Feb, 2023
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
- Something that helps you drag a pointer on live data to get the color of the object or the thing
- 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.
- 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.
- 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.
- 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.
- 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:
- The app that initially had the data is referred to as the source app. It's here when the slog begins.
- 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.
Similar Reads
How to Use Dagger Library in Android App?
When we create a new Android Project, eventually we start accumulating different-different dependencies to get certain functionalities, but over time managing them becomes cumbersome, thus an injection framework like Dagger comes into play. However, setting up an injection service like Dagger requir
5 min read
Android Drag and Drop with Kotlin
In most Android applications where data is displayed in the form of a list format, there is a functionality with the help of which we can simply drag and drop any item from that list to any specific position within the list. To implement this type of drag-and-drop functionality we have to use a Drag
5 min read
How to Use Canvas API in Android Apps?
Canvas API is also one of the most used in Android. The name of the API itself tells us that the API is being used for drawing on the drawing board. With the help of this API, we can draw different types of shapes and create custom UI components that are not present in Android. In this article, we w
5 min read
How To Add Apps To Android Auto?
In today's digital era, Android Auto is a beneficial tool that enables you to run your favourite phone apps on the car's infotainment screen. You can listen to music or podcasts, employ navigation services, and drive attentively. Here is how you can add more apps to your Android Auto.Table of Conten
5 min read
How To Make An Android App
Have you always wanted to make an Android app but got lost in the complexity of the Android Studio or the technical jargon used in the development process? Don't worry, you have come to the right place. We are going to help you get started with your first Android app.The app that we are going to mak
7 min read
How to Build a Simple Notes App in Android?
Notes app is used for making short text notes, updating when you need them, and trashing when you are done. It can be used for various functions as you can add your to-do list in this app, some important notes for future reference, etc. The app is very useful in some cases like when you want quick a
9 min read
How to Add Drag And Drop Feature in Android RecyclerView?
Drag And Drop feature is very helpful. It is very simple and easy to implement. It is used in many apps that are famous, and if we're doing some project it is very convenient to implement it. You should know the RecyclerAdapter Class. A sample video is given below to get an idea about what we are go
4 min read
How to Insert/Append Data to Excel using Android?
File handling in Java is used to read and write data to a file. The particular file class from the package called java.io allows us to handle and work with different formats of files. File handling allows users to store data permanently in a file. And the best or suggested document for storing data
3 min read
How to Use putExtra() and getExtra() For String Data in Android?
Many times in android applications we have to pass data from one activity to another for performing some operations. There are several different ways that are used to give data from one activity to another activity. In this article, we will specifically take a look at How to use putExtra() and getEx
5 min read
How to Create a Unlock Slide-Bar in Android?
A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys. SeekBar is a useful user interface element in Android that allows the selection of integer values using a natural user in
5 min read