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.
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.
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.
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.
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.
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.
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.
Before calling startDrag a shadowBuilder
object should be created. Pass the view instance to View.DragShadowBuilder(view)
to show drag shadow.
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.
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.
<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; } }
Download Android Sample Project Code for Drag and Drop
Comments are closed for "Android Drag and Drop".
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.
Happy Valentines Day Joe!
Big like for your tutorials especially for design patterns part.
Tanx buddy.
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
Anna Seriously u r great please i have some doubt in JQuery.. if u r means contact my mail id……….
Very good tutorial and it is very helpful to me
thanx a lot
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.
Sooperb and plain simple tutorail
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]
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]
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”
Thanks! :)
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.. :-)
Thank you for such a nice & easy tut :-)
Change your layout ‘Linear’ to ‘Relative’.. That ‘ll do.
Man, these texts of yours are so helpfull… thanks very much.
Hi Joe,
Your tutorial is the best tutorial so far. Each word is articulated with precision. Thanks.
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.
nice tutorial, all ur android tutorials are best
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?
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.
hi Joe
I want to drag and drop a file from one device to another device.can you plz help me……..
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.
Nice Help sir. Best drag and drop tutorial in the net.
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,
Excellent work man…. Thanks and pls write more similar tutorials.
Change the android:minSdkVersion in AndroidMenifest.xml to “11”. It is not working in “8”
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);
}
}
}
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?
In simple, You are Awesome Sir !!!
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)?
Nice Android tutorial. Really helps…
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?
Hi , I am developed drag and drop. But, I have to reset back to previous position after dropping. Please tell me.
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 .
You have given such a beautiful Android tutorial.