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.


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.


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.


<RelativeLayout xmlns:tools=""
    tools:context=".MainActivity" >

        android:orientation="vertical" >
        android:text="@string/dragtext" />

        android:orientation="vertical" >


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

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); 
		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(); 
	LinearLayout container = (LinearLayout) layoutview; 

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");
	      case DragEvent.ACTION_DRAG_ENTERED:
	    	  Log.d(LOGCAT, "Drag event entered into "+layoutview.toString());
	      case DragEvent.ACTION_DRAG_EXITED:
	    	  Log.d(LOGCAT, "Drag event exited from "+layoutview.toString());
	      case DragEvent.ACTION_DROP:
	    	Log.d(LOGCAT, "Dropped");
	    	View view = (View) dragevent.getLocalState();
	        ViewGroup owner = (ViewGroup) view.getParent();
	        LinearLayout container = (LinearLayout) layoutview;
	      case DragEvent.ACTION_DRAG_ENDED:
	    		  Log.d(LOGCAT, "Drag ended");
	      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.

Comments on "Android Drag and Drop" Tutorial:

  1. Meera 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.

  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 topic at once.


  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:

    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!!!!

  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{}: java.lang.ClassNotFoundException: in loader dalvik.system.PathClassLoader[/data/app/]

  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{}: java.lang.ClassNotFoundException: in loader dalvik.system.PathClassLoader[/data/app/]

  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. anotherashia 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. deo says:

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

  14. Preethika says:

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

  15. Azahar says:

    your project gives error when imported.

  16. Azahar says:

    error is require API level 11. but have API level 17

  17. Daniel says:

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

  18. Nidhi says:

    Hi Joe,

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

  19. 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.

  20. ajay says:

    nice tutorial

  21. 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.

    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?

  22. MMakati says:

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

  23. 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.

  24. srimannarayana says:

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

  25. 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.

  26. Anonymous says:

    Nice Help sir

  27. Dheeraj Sharma says:

    Nice Help sir

  28. Cheby says:


    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?


  29. Arjun says:

    Excellent work man….

  30. Anonymous says:

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

  31. 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;

    public void onCreate(Bundle savedInstanceState) {

    ima = (ImageView)findViewById(;
    // Sets the tag

    ima.setOnTouchListener(new View.OnTouchListener() {

    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)
    return true;
    return false;

    // Create and set the drag event listener for the View
    ima.setOnDragListener( new OnDragListener(){
    public boolean onDrag(View v, DragEvent event){
    case DragEvent.ACTION_DRAG_STARTED:
    Log.d(msg, “Action is DragEvent.ACTION_DRAG_STARTED”);
    // Do nothing

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

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

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

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

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

    View view=(View) event.getLocalState();
    return true;
    default: break;
    return true;

    private class DragShadow extends View.DragShadowBuilder

    public DragShadow(View view) {

    public void onDrawShadow(Canvas canvas) {

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

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

    shadowSize.set(width, height);


  32. Nitish says:

    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?

  33. Farhad says:

    In simple, You are Awesome Sir !!!

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

  35. dummy says:

    Nice tutorial. Really helps…

  36. Anonymous 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.
    please reply soon….

  37. Gangadhar says:

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

  38. 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 .

Your Comment

↑ Go to top