Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Steps to Drag and Drop Process
2.1.
Started
2.2.
Continuing
2.3.
Dropped
2.4.
Ended
3.
Drag Events Class
4.
Listening for Drag Event
5.
Starting a Drag Event
6.
Frequently Asked Questions
6.1.
Is drag & drop supported on mobile devices?
6.2.
Mention the use of Action_drag_entered?
6.3.
What is jQuery for mobile?
6.4.
What is the purpose of drag and drop?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Android Drag and Drop Feature

Author Ankit Mishra
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

When a user makes a UI gesture that your software perceives as a signal to begin dragging data, Drag and Drop operation begins. The app responds by informing the system that a drag-and-drop action is about to begin. To obtain a representation of the data being dragged, the system contacts your app (a drag shadow). The system delivers drag events to drag event listeners and callback methods associated with the View objects in the layout when the user moves the drag shadow across the app's layout. When the user completes the drag and drop action, the system transfers the data to the target if the user releases the drag shadow over a view that can take the data (a drop target).

The Android drag/drop framework allows your users to drag and drop data from one View to another in the current layout. Drag & drop of views onto other views or view groups is now available in API 11. To provide drag-and-drop capabilities, the framework includes the following three key components:

  • Drag event class.
  • Drag listeners.
  • Helper methods and classes.

View.OnDragListener is used to build a drag event listener. The setOnDragListener() function of the View object is used to create a drop target listener. An onDragEvent() callback method is available for each view in the layout. In general, the Drag and Drop process begins when users make motions that are detected as a signal to begin dragging data, and the application notifies the system.

When the drag begins, the system sends drag events to the drag event listeners or call-back methods of each View in the layout. 

Source

Steps to Drag and Drop Process

Started

When we begin dragging an item in layout, our application will call the startDrag() method to instruct the system to begin dragging. Data to be dragged, the metadata for this data, and a call-back for creating the drag shadow will be provided as parameters to the startDrag() method.

Your application calls startDragAndDrop() to instruct the system to start a drag and drop operation responding to a user's drag motion. The arguments for the method offer the following:

  • The information to be dragged
  • A callback is used to draw the drag shadow.
  • Metadata that describes the data that was dragged

The system will then send a drag event with the action type ACTION_DRAG_STARTED to all view objects in the current layout's drag event listeners. The drag event listener must return true to continue receiving drag events, including a possible drop event. It must also register with the system because only registered listeners continue to receive drag events. Listeners can also change the appearance of their View object at this point to indicate that they can accept a drop event.

If the drag event listener returns false, the current operation will not receive any drag events until the system provides a drag event with the action type ACTION_DRAG_ENDED. By sending a false, the listener tells to the system that this is not interested in drag operation, and also does not want to accept dragged data.

Also Read, android operating system

Continuing

The user keeps dragging. The system transmits one or more drag events to the target's drag event listener as the drag shadow intersects with the bounding box of a drop target. In response to the events, the listener may choose to change the appearance of the drop target View. The listener can react just by highlighting the View if the event signals that the drag shadow has entered in the bounding box of the drop target (action type ACTION_DRAG_ENTERED).

Dropped

Within the bounding box of a View, when the user releases the dragged item. The system sends a drag event with the action type ACTION_DROP to the View object's listener.

Ended

The system sends a drag event with action type ACTION_DRAG_ENDED once the user releases the drag shadow, and the system sends a drag event with action type ACTION_DROP (if necessary) to indicate that the drag and drop operation is complete. This is done regardless of where the drag shadow was released. Even if the listener has already received the ACTION_DROP event, the event is sent to every listener who is registered to receive drag events.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Drag Events Class

The system sends a drag event in the form of a DragEvent object, which has an action type that explains what happens throughout the drag and drop process. The object may additionally contain extra data, depending on the action type.

The DragEvent object is given to event listeners. Listeners can acquire the action type by calling DragEvent#getAction (). The DragEvent class has six possible values defined by constants.

The data and metadata that your application has provided to the system in the startDragAndDrop() method are likewise stored in the DragEvent object.

Listening for Drag Event

If you want any of your views in a Layout to respond to the Drag event, make sure that your view implements View. OnDragListener or callback function onDragEvent(DragEvent) When the system calls the method or listener, it sends a DragEvent object to them, as mentioned above. The View object can contain both a listener and a callback method. If this happens, the system will call the listener first, then the defined callback if the listener returns true.

The onDragEvent(DragEvent) function and View are combined.

The combination of onTouchEvent() and View is comparable to OnDragListener.

In older Android versions, OnTouchListener was used with touch events.

Starting a Drag Event

To begin, make a ClipData and a ClipData.Item, The data being transported item. Provide metadata for the ClipData object, which is kept in a ClipDescription object within the ClipData. Use null instead of an actual object for a drag and drop action that does not indicate data migration.

You can then either extend or extend View.DragShadowBuilder, You can use View or DragShadowBuilder to create a drag shadow for dragging the view.

DragShadowBuilder(View) creates a default drag shadow with the touchpoint centered in it, the same size as the View argument supplied to it.

The following example shows the functionality of a simple Drag & Drop using View.setOnLongClickListener(), View.setOnTouchListener() and View.OnDragEventListener().

  • Create an Android application using the Android Studio IDE and name it My Application under the package com.example.saira 000.myapplication.
  • Add the code to define event listeners and callback methods for the logo image used in the example to the src/MainActivity.java file.
  • Paste abc.png into the res/drawable-* directories. If you wish to provide images for multiple devices, you can use images with varied resolutions.
  • Modify the res/layout/activity main.xml layout XML file to define the default view of the logo images.
  • Open the application to launch the Android emulator and check the results of the adjustments you made.

Following will be the content of the modified main activity file at src/MainActivity.java. This file can include each of fundamental lifecycle methods in creation.

package com.example.saira_000.myapplication;


import android.app.Activity;


import android.content.ClipData;
import android.content.ClipDescription;


import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;


import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;


import android.widget.ImageView;
import android.widget.RelativeLayout;


public class MainActivity extends Activity {
  ImageView img;
  String msg;
  private android.widget.RelativeLayout.LayoutParams layoutParams;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     img=(ImageView)findViewById(R.id.imageView);
     
     img.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
           ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());
           String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
           
           ClipData dragData = new ClipData(v.getTag().toString(),mimeTypes, item);
           View.DragShadowBuilder myShadow = new View.DragShadowBuilder(img);
           
           v.startDrag(dragData,myShadow,null,0);
           return true;
        }
     });
     
     img.setOnDragListener(new View.OnDragListener() {
        @Override
        public boolean onDrag(View v, DragEvent event) {
           switch(event.getAction()) {
              case DragEvent.ACTION_DRAG_STARTED:
              layoutParams = (RelativeLayout.LayoutParams)v.getLayoutParams();
              Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED");
             
              // Do nothing
              break;
             
              case DragEvent.ACTION_DRAG_ENTERED:
              Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
              int x_cord = (int) event.getX();
              int y_cord = (int) event.getY();
              break;
             
              case DragEvent.ACTION_DRAG_EXITED :
              Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
              x_cord = (int) event.getX();
              y_cord = (int) event.getY();
              layoutParams.leftMargin = x_cord;
              layoutParams.topMargin = y_cord;
              v.setLayoutParams(layoutParams);
              break;
             
              case DragEvent.ACTION_DRAG_LOCATION  :
              Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
              x_cord = (int) event.getX();
              y_cord = (int) event.getY();
              break;
             
              case DragEvent.ACTION_DRAG_ENDED   :
              Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
             
              // Do nothing
              break;
             
              case DragEvent.ACTION_DROP:
              Log.d(msg, "ACTION_DROP event");
             
              // Do nothing
              break;
              default: break;
           }
           return true;
        }
     });
     
     img.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
           if (event.getAction() == MotionEvent.ACTION_DOWN) {
              ClipData data = ClipData.newPlainText("", "");
              View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(img);
             
              img.startDrag(data, shadowBuilder, img, 0);
              img.setVisibility(View.INVISIBLE);
              return true;
           } else {
              return false;
           }
        }
     });
  }
}

Following will be the content of the res/layout/activity_main.xml file −

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  android:paddingBottom="@dimen/activity_vertical_margin"
  tools:context=".MainActivity">
 
  <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Drag and Drop Example"
     android:id="@+id/textView"
     android:layout_alignParentTop="true"
     android:layout_centerHorizontal="true"
     android:textSize="30dp" />
     
  <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Coding Ninjas"
     android:id="@+id/textView2"
     android:layout_below="@+id/textView"
     android:layout_centerHorizontal="true"
     android:textSize="30dp"
     android:textColor="#fc8403" />>
     
  <ImageView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/imageView"
     android:src="@drawable/abc"
     android:layout_below="@+id/textView2"
     android:layout_alignRight="@+id/textView2"
     android:layout_alignEnd="@+id/textView2"
     android:layout_alignLeft="@+id/textView2"
     android:layout_alignStart="@+id/textView2" />


</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new constants which are −

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">My Application</string>
</resources>

Following is the default content of the AndroidManifest.xml −

Here-->  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.saira_000.myapplication" >
     
  <application
     android:allowBackup="true"
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name"
     android:theme="@style/AppTheme" >
     
     <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
     
        <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
     
     </activity>
     
  </application>
</manifest>

Let's try to run your My Application. I have assumed you had created your AVD while doing the environment setup. Open one of your project activity files and click Run Eclipse Run Icon from the toolbar to run the app from Android Studio. Android Studio installs the app on your AVD and starts it, and if everything is fine with your setup and application, it will display the following Emulator window −

Now, long click on the displayed Coding ninjas logo, and you'll see that the logo image shifts a little after 1 second of long clicking; this is the moment to begin dragging the image. You can move it about the screen by dragging it and dropping it.

Frequently Asked Questions

Is drag & drop supported on mobile devices?

Most desktop browsers support drag'n'drop thanks to the HTML 5 drag'n'drop API. Unfortunately, it isn't supported by the majority of mobile browsers.

Mention the use of Action_drag_entered?

Before receiving any ACTION-DRAG-LOCATION events, a View receives an ACTION_DRAG_ENTERED event. Once the user drags the drag shadow out of the bounding box of the View object or into a daughter view that can receive the data, the system stops issuing ACTION_DRAG_LOCATION events to the View.

What is jQuery for mobile?

jQuery Mobile is an HTML5-based user interface solution for creating responsive websites and apps that work on smartphones, tablets, or computers. It features Ajax navigation with page transitions, touch events, and numerous widgets built on the rock-solid jQuery and jQuery UI framework.

What is the purpose of drag and drop?

Drag and drop is a technique for moving computer files or images from one location to another by clicking and dragging them across the screen with the mouse. It's as simple as dragging and dropping applications onto an iPod.

Conclusion

In this article, we have extensively discussed the exclusive Drag and Drop feature of Android, Code behind the scenes of working of the Drag and Drop.

To read more about Android and Subtopics, reach here, Android Development40 days Archives.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses, refer to the mock test and problems; look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning!

Previous article
Google Maps APIs in Android
Next article
Notifications in Android
Live masterclass