Android Drag and Drop

Last modified on June 26th, 2015 by Joe.

This Android tutorial is to help you learn about how to use drag and drop feature in an Android application. Drag and drop feature is a way of interacting with UI for long with computers. Now in the Mobile and touch screen revolution, drag and drop is becoming an important UI gesture. Lots of games are using drag and drop as a primary way of playing the game. Angry birds is one such popular game which uses drag and drop as its primary game control.

Just a history snippet about drag and drop. In Windows OS 2.0 version, the drag and drop gesture was first introduced in a shareware program (WinTools) by Jeffrey Greenberg.

drag and drop

Drag and Drop Android API

In this tutorial, we shall learn about the Android APIs behind drag and drop, and how to use it by creating a sample Android application. OnTouchListener and OnDragListener are the key interfaces that needs to be implemented for drag and drop. These are callback interfaces and it has methods such as onLongPress and onTouch which will be triggered by Android when user does a drag and drop. Essentially with a drag and drop, we use it to move an Android View from one UI point to another.

Steps for Drag and Drop Implementation

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

Step 1. Design Android Layout

The bounding space is nothing but any view like Linear layout, Relative layout, listview or like such views, which will contain the view for drag and drop. When the user touches this view, the drag event will be triggered.

Step 2. Create Android Activity

An Android activity class should be created and let it to implement the required drag and drop listener classes. These interfaces contains the drag and drop call back functions that will be called by the runtime when the event occurs.

Step 3. Define Drag and Drop Callbacks

OnTouchListener and OnDragListener are the two interfaces that needs to be implemented for drag and drop callback. 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 passed.

onTouch() Drag and Drop Callback

When the user presses the View to be dragged, the methods onTouch() and onLongClick() will be invoked by the Android runtime. We should have our application logic inside the method and that will executed on drag callback.

How do we pass meta data onDrag?

Clip data should be created and it should have data to be dragged and clip description. This clip data can be accessed on leaving the drag control using getClipData(). This clip data is optional. If the use case requires to pass information, then this can be used. 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. Pass the view instance to View.DragShadowBuilder(view) to show drag shadow.

onDrag() Drag and Drop Callback

After the start of the drag is intimated to 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(). Those actions have different states and they are listed as follows.

Android Drag and Drop Example

Download Android Sample Project Code for Drag and Drop

In this example Android application, I will demonstrate the drag and drop gesture by moving a TextView from one LinearLayout to another.

Our Android activity has Two LinearLayout Views which are identified as pinkLayout and yellowLayout. Then a TextView to be created with the pinkLayout.

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>

This view will be used to set the listeners OnTouchListener and OnDragListener which will be the Android callback handlers for drag and drop. Set those listeners to the view.

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); 
} 

Define, the onTouch(), onDrag(), drag and drop call back methods.

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; 
	} 
} 

We can use MotionEvent to handle various actions. 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().

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. 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. Following is the complete drag and drop Android activity class.

package com.javapapers.android.drag_drop;

import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.View.DragShadowBuilder;
import android.widget.LinearLayout;
import android.util.Log;
import com.javapapers.android.drag_drop.R;


public class MainActivity extends Activity implements OnTouchListener,OnDragListener{
	private static final String LOGCAT = null;
	@Override
	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);
	}
	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;
		    }
	}  
    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;
    }
}

Android Drag and Drop Example App Output

drag and drop output

Download Android Sample Project Code for Drag and Drop

Comments on "Android Drag and Drop"

  1. Anderson says:

    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. H.E says:

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

  3. Vivek says:

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

    Thanks,
    Vivek

  4. C SATHIYARAJA says:

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

  5. niranjan yadav B says:

    Very good tutorial and it is very helpful to me

    thanx a lot

  6. hermie says:

    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.

  7. Bilal Ahmed says:

    Sooperb and plain simple tutorail

  8. !0may says:

    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]

  9. Dhaval says:

    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]

  10. pavan says:

    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”

  11. Jones says:

    Thanks! :)

  12. deo says:

    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.. :-)

  13. Miller says:

    Thank you for such a nice & easy tut :-)

  14. Preethika says:

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

  15. Daniel says:

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

  16. Brown says:

    Hi Joe,

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

  17. Nidhi says:

    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.

  18. Smith says:

    nice tutorial, all ur android tutorials are best

  19. Aniket Bhsoale says:

    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?

  20. MMakati says:

    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.

  21. srimannarayana says:

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

  22. roboto says:

    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.

  23. Dheeraj Sharma says:

    Nice Help sir. Best drag and drop tutorial in the net.

  24. Cheby says:

    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,

  25. Arjun says:

    Excellent work man…. Thanks and pls write more similar tutorials.

  26. Harris says:

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

  27. Akshay says:

    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);
    }

    }
    }

  28. Nitish says:

    Hi Joe,

    First of all I would like to say thanks for providing clear and in depth understanding of the framework. All your android tutorials are great.

    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?

  29. Farhad says:

    In simple, You are Awesome Sir !!!

  30. Namit says:

    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)?

  31. Honey says:

    Nice Android tutorial. Really helps…

  32. Walker says:

    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.
    Can you please write Android tutorial for this?

  33. Gangadhar says:

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

  34. md.hussain says:

    Sir actually i want to build dragshadow from original resources according to drag and drop of it’s original sizes .but it not happening by me if you have any solution plz mailed me .

  35. nagesh says:

    You have given such a beautiful Android tutorial.

Comments are closed for "Android Drag and Drop".