Android Drag and Drop

This tutorial speaks about Drag and Drop capability of android applications and categorized under Android user interface. In Windows OS, the drag and drop operation was first introduced in a shareware program (WinTools) by Jeffrey Greenberg on Windows 2.0. Drag and drop operation is highly prevalent in graphical user interfaces. In this Android tutorial, we shall see how to make it happen in an Android app.

drag and drop

Drag and drop implementation uses events triggered by onLongPress or onTouch Android callback functions. The triggered events are handled by the set of listener classes and their corresponding callback functions. At low level, drag and drop is used to move data from one view to another.

Steps for Drag and Drop Implementation

  1. Design Layout: Design layout that contains two or more bounding spaces and the view to be dragged.
  2. Create Activity: Create activity which implements required listener classes.
  3. Define Callbacks: Define call back functions onTouch() and onDrag().

Step 1. Design Layout

  • Need to create two or more bounding spaces.
  • Create Android views to be dragged between available bounding spaces.

First, open the xml file needed for the design. The bounding space is nothing but any view like Linear layout, Relative layout, listview or like such views. These views should be dragged from the left panel in the graphical layout. And then the dimensions are needed to be given for the width, height and padding attribute of the views to separate them from one another. Then, any views like TextView, ImageView or any other should be placed inside the bounding area. So when the user holds on to this view for little bit of time, the drag event will be triggered.

Step 2. Create Activity

In this step, an activity class should be created and let it to implement the required listener classes; for example, onLongClickListener or onDragListener and so on. These classes will be set to the view objects. This will be done in onCreate callback function. Because the listener classes are needed to be set to the view objects on launching the activity itself. Then only the system can dispatch the events to the listener classes during the drag.

Step 3. Define Callbacks

OnTouchListener and OnDragListener are the two interfaces that needs to be implemented. These two Android interfaces contain one method each, respectively onTouch and onDrag. We can even use OnLongClickListener, if so then the respective method to be implemented is onLongClick. For onTouch event, MotionEvent object and the View object should be sent as arguments. For onDrag event the DragEvent object and View object should be sent.

Ads by Google

onTouch()

When the user presses the View to be dragged the methods like onTouch() or onLongClick() will be invoked by the Android runtime.

How do we pass meta data onDrag?

To achieve that, in the listener method implementation, a clip data should be created. It should have the data to be dragged and clip description. This clip data can be accessed on leaving the drag control using getClipData().

This clip data work is optional. If the use case requires to pass information, then this can be done. If created, the data will be sent via the startDrag() method. On invoking the startDrag(), the application will intimate the system about the start of the drag.

How do we show drag shadow?

Before calling startDrag a shadowBuilder object should be created. This class has two type constructors. One is a no argument constructor which will be called by View.DragShadowBuilder(). The another is the single argument constructor which holds the Android View object as its argument like View.DragShadowBuilder(view).

Based on the type of constructor call the shadow to be shown during the drag will differ. If the later constructor is used, then the shadow will be as like as the view on which the user made a long press. If the former constructor is used, then the shadow will not be shown on the screen.

After creating shadowBuilder object the startDrag method will be invoked. This method holds data, shadowBuilder object, local state and flags as its argument. Immediately the following two methods of shadow builder will be invoked one after another.

  • onProvideShadowMetrics() – It holds two arguments as dimensions and touch_point. Both are point objects. The dimension provides the width and height of the drag shadow and the touch_point points the drag position.
  • onDrawShadow() – This method will be invoked after onProvideShadowMetrics(). This method use the metrics provided by the above method and let the system to create the canvas object. Canvas is the only argument to this method to draw the shadow.

onDrag()

After the information about the start of the drag is intimated to the Android runtime, immediately it will allow the DragEventListener to handle the drag event using the onDrag() method. It holds two arguments as View and DragEvent object. On handling the drag event there are several possible actions. That action is returned by the method getAction(). This method can be invoked from the drag event object which is one of the argument of onDrag method. Those actions have different states and they are listed as follows.

  • ACTION_DRAG_STARTED – This action will be returned after the startDrag method is invoked.
  • ACTION_DRAG_ENTERED – Whenever the Android View to be dragged enters into a new bounding space, this action will be returned.
  • ACTION_DRAG_LOCATION – This will be returned for each touch point during the drag. It holds the x,y coordinates of the drag position.
  • ACTION_DRAG_EXITED – Once the dragged view leave some bounding space or layout, then this action will be returned.
  • ACTION_DROP – Once the finger release the hold from drag, then this is returned.
  • ACTION_DRAG_ENDED – This action is the end of the Android drag and drop cycle.

Android Drag and Drop Example

Download Android Sample Project Code for Drag and Drop

Let us see an example an implementation of Android drag and drop by moving a TextView from one LinearLayout to another.

At first step, the activity_main.xml file is designed by creating Two LinearLayout Views which is identified as pinkLayout and yellowLayout. These two layouts are differed by setting width, height, padding and background properties. And then a TextView will be created with the pinkLayout. Finally the code for this xml file will be as follows.

activity_main.xml

 
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/pinkLayout"
        android:layout_width="fill_parent"
        android:layout_height="210dp"
        android:background="#FF8989"
        android:orientation="vertical" >
        
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/dragtext" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/yellowLayout"
        android:layout_width="fill_parent"
        android:layout_height="250dp"
        android:layout_marginTop="210dp"
        android:background="#FFCC00"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

The views created in design will be used to set the set of listener named as OnTouchListener, OnDragListener. For that, an activity subclass ia created which implements both of the listener classes stated above. Then, OnTouchListener is set to the TextView using the setOnTouchListener() method. Similarly, OnDragListener is set to the two LinearLayouts by setOnDragListener() method. As discussed already, set the listener classes inside onCreate() method. And, ensure that, the required listener classes are imported properly. code will be shown as follows.

protected void onCreate(Bundle savedInstanceState) { 
	super.onCreate(savedInstanceState); 
	setContentView(R.layout.activity_main); 
	findViewById(R.id.textView1).setOnTouchListener(this); 
	findViewById(R.id.pinkLayout).setOnDragListener(this); 
	findViewById(R.id.yellowLayout).setOnDragListener(this); 
} 

In the third step the onTouch() and onDrag() methods are defined.

In onTouch() method, the application intimates about start of the drag. This is done while calling the startDrag() method. This method includes some set of arguments like as follows.

  • Data to be dragged(It is null here).
  • Shadow Buider object created by DragShadowBuilder.
  • Local State (Drag Location).
  • Flags

This method can be defined with the following code,

public boolean onTouch(View view, MotionEvent motionEvent) { 
	if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { 
		DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); 
		view.startDrag(null, shadowBuilder, view, 0); 
		view.setVisibility(View.INVISIBLE); 
		return true; 
	} else { 
		return false; 
	} 
} 

When the event action is ACTION_DOWN, the above line of code will be executed. After the drag is started, the original view being dragged is set as invisible by the setVisibility() function with the argument view.INVISIBLE.

When the Android system dispatches the event information to the DragListener, then onDrag() method will be invoked. Since there are so many action among entire drag and drop operation, a switch case is created to cover all possible actions. The current action is got by the dragevent.getAction(). To drop the view, the following code is needed inside the dragevent.ACTION_DROP case.

case DragEvent.ACTION_DROP: 
	Log.d(LOGCAT, "Dropped"); 
	View view = (View) dragevent.getLocalState(); 
	ViewGroup owner = (ViewGroup) view.getParent(); 
	owner.removeView(view); 
	LinearLayout container = (LinearLayout) layoutview; 
	container.addView(view); 
	view.setVisibility(View.VISIBLE); 
	break;

On drop, the current view state during the drag is retrieved by the getLocalState() method. Then, the parent view of the dragged view will be captured by getParent() method and stored into a ViewGroup. The view after drop will be updated by the removeView() and addView() methods. The initial view position before drop event, is removed from the parent and positioned into required bounding area which is here the LinearLayout.

The entire onDrag() method can be defined as follows.

    public boolean onDrag(View layoutview, DragEvent dragevent) {
	      int action = dragevent.getAction();
	      switch (action) {
	      case DragEvent.ACTION_DRAG_STARTED:
	          Log.d(LOGCAT, "Drag event started");
	    	break;
	      case DragEvent.ACTION_DRAG_ENTERED:
	    	  Log.d(LOGCAT, "Drag event entered into "+layoutview.toString());
	    	break;
	      case DragEvent.ACTION_DRAG_EXITED:
	    	  Log.d(LOGCAT, "Drag event exited from "+layoutview.toString());
	    	break;
	      case DragEvent.ACTION_DROP:
	    	Log.d(LOGCAT, "Dropped");
	    	View view = (View) dragevent.getLocalState();
	        ViewGroup owner = (ViewGroup) view.getParent();
	        owner.removeView(view);
	        LinearLayout container = (LinearLayout) layoutview;
	        container.addView(view);
	        view.setVisibility(View.VISIBLE);
	        break;
	      case DragEvent.ACTION_DRAG_ENDED:
	    		  Log.d(LOGCAT, "Drag ended");
		      break;
	      default:
	        break;
	      }
	      return true;
    }

To continue with the operation of OnDragEventListener, the onDrag() method should return true after each action.

Android Drag and Drop Output

drag and drop output

Download Android Sample Project Code for Drag and Drop

This Android tutorial was added on 14/02/2013.

previous post: Java Weak Reference

next post: try-with-resources

38 comments on “Android Drag and Drop

  1. Hey Joe,

    This is the best ever Android tutorial I have read. You have covered the drag and drop topic completely and so crystal clear. Amazing work.

    Please write more on Android.
    Thanks,
    Meera.

  2. Happy Valentines Day Joe!
    Big like for your tutorials especially for design patterns part.
    Tanx buddy.

  3. Hi ,As You have very good example for Android ,Please Add Android in Menu item ,so we can find all Android topic at once.

    Thanks,
    Vivek

  4. Anna Seriously u r great please i have some doubt in JQuery.. if u r means contact my mail id……….

  5. Very good tutorial and it is very helpful to me

    thanx a lot

  6. hello.
    I was unable to run this program on my eclipse. it kept crashing the emulator. Did anyone else get this error as well. Please reply. Very urgent!!!!
    Thanks.

    • I Have the same problem the App crashes on eclipse. Below is the log…
      04-27 11:01:45.155: E/AndroidRuntime(523): FATAL EXCEPTION: main
      04-27 11:01:45.155: E/AndroidRuntime(523): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.javapapers.android.drag_drop/com.javapapers.android.drag_drop.MainActivity}: java.lang.ClassNotFoundException: com.javapapers.android.drag_drop.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.javapapers.android.drag_drop-1.apk]

      • Change the android:minSdkVersion in AndroidMenifest.xml to “11″. It is not working in “8″

  7. I Have the same problem the App crashes on eclipse. Below is the log…
    04-27 11:01:45.155: E/AndroidRuntime(523): FATAL EXCEPTION: main
    04-27 11:01:45.155: E/AndroidRuntime(523): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.javapapers.android.drag_drop/com.javapapers.android.drag_drop.MainActivity}: java.lang.ClassNotFoundException: com.javapapers.android.drag_drop.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.javapapers.android.drag_drop-1.apk]

  8. hai sir
    i Download your code and run that project but it gives force shut down.when i debug that project that shows error called “source not found”

  9. Hey thanks for this awesome tutorial. But with above code when we drop textVeiw, by default it goes into Top-Left corner.. But I want to place it where user has dropped(i.e. anywhere on screen) How can I achieve that? Please help..
    Thanks in advance.. :-)

    • Change your layout ‘Linear’ to ‘Relative’.. That ‘ll do.

      • I tried changing to relative but still it goes to top-left part

  10. Man, these texts of yours are so helpfull… thanks very much.

  11. Hi Joe,

    Your tutorial is the best tutorial so far. Each word is articulated with precision. Thanks.

  12. Hi Joe,

    How to drag from fragment to canvas? Is it possible to have multiple fragments(hide/show) with canvas? How to implement this? I will really appreciate your reply.

  13. I have a query.
    I have a layout at center of screen.
    I want to drag a whole layout to left,right,up,down anywhere.

    Now,
    When I move layout to left from center I want to show
    one Image on it (dislike).

    When I move layout to right from center I want to show
    one Image on it (like).

    How to do it?

  14. Nice tutorial, but everytime I drag it to another layout it goes to upper left corner. I want to place where I dropped the text.

  15. hi Joe
    I want to drag and drop a file from one device to another device.can you plz help me……..

  16. Hi, nice tutorial, but there is another approach yet how to provide drag and drop even on old versions of android. By overriding onLayout and onMeasure on ViewGroup. As a drag item placeholder you can use items window put into the WindowManager. If you are interested in check out github example https://github.com/theredsunrise/AndroidCoolDragAndDropGridView

  17. Hi,

    Amazing work, the best Tut I’ve found!
    Just a question, what do I change if I want the TextView to be dragged and dropped just once?

    Cheers,

  18. I have following code for dragging and dropping the image view in same layout but it get invisible at ACTION_DROP event will you please tell me where I’m getting wrong..

    public class MainActivity extends Activity{
    ImageView ima;
    private static final String IMAGEVIEW_TAG = “Android Logo”;
    String msg;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ima = (ImageView)findViewById(R.id.iv_logo);
    // Sets the tag
    ima.setTag(IMAGEVIEW_TAG);

    ima.setOnTouchListener(new View.OnTouchListener() {

    @SuppressLint(“InlinedApi”)
    @Override
    public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
    ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());

    String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
    ClipData dragData = new ClipData(v.getTag().toString(), mimeTypes, item);
    // Instantiates the drag shadow builder.
    DragShadow dragShadow=new DragShadow(v);

    // Starts the drag
    v.startDrag(dragData // the data to be dragged
    , dragShadow // the drag shadow builder
    , v // no need to use local data
    , 0 // flags (not currently used, set to 0)
    );
    v.setVisibility(View.INVISIBLE);
    return true;
    }
    else{
    return false;
    }
    }
    });

    // Create and set the drag event listener for the View
    ima.setOnDragListener( new OnDragListener(){
    @Override
    public boolean onDrag(View v, DragEvent event){
    switch(event.getAction())
    {
    case DragEvent.ACTION_DRAG_STARTED:
    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”);
    v.invalidate();
    break;

    case DragEvent.ACTION_DRAG_EXITED :
    Log.d(msg, “Action is DragEvent.ACTION_DRAG_EXITED”);
    v.invalidate();
    break;

    case DragEvent.ACTION_DRAG_LOCATION :
    Log.d(msg, “Action is DragEvent.ACTION_DRAG_LOCATION”);
    break;

    case DragEvent.ACTION_DRAG_ENDED :
    Log.d(msg, “Action is DragEvent.ACTION_DRAG_ENDED”);
    v.invalidate();
    // Do nothing
    break;

    case DragEvent.ACTION_DROP:
    Log.d(msg, “ACTION_DROP event”);

    View view=(View) event.getLocalState();
    view.setVisibility(View.VISIBLE);
    view.invalidate();
    return true;
    default: break;
    }
    return true;
    }
    });
    }

    private class DragShadow extends View.DragShadowBuilder
    {

    public DragShadow(View view) {
    super(view);
    }

    @Override
    public void onDrawShadow(Canvas canvas) {
    super.onDrawShadow(canvas);
    }

    @Override
    public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
    View v= getView();

    int height=v.getHeight();
    int width=v.getWidth();

    shadowSize.set(width, height);
    shadowTouchPoint.set((int)width/2,(int)height/2);
    }

    }
    }

  19. Hi Joe,

    First of all I would like to say thanks for providing clear and in depth understanding of the framework.

    I have a query, I want to get the last position to which view is dragged. As per docs getX() and getY() will not return valid value on ACTION_DRAG_ENDED. So, is there anr alternative through which I can get these values?

  20. While doing dragging, is there a way to cancel the drag operations using some external operation or is there a way to abort the dragging, without releasing the view (which is getting dragged)?

  21. i want a bubble interface which remains on top of all layout and while moving the bubble to any image or word it copies it .the bubble does all for you . IS there any class for that.
    please reply soon….

  22. Hi , I am developed drag and drop. But, I have to reset back to previous position after dropping. Please tell me.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>