Android Drag and Drop example and tutorial


Introduction 
          Android Drag and Drop framework lets the user to move data from one view to another within the current layout using a graphical drag and drop gesture. When you start a drag, you include both the data you are moving and metadata describing this data as part of the call to the system.

This drag and drop gesture is used across several android applications, especially in android games.
           In this tutorial we will see how to implement drag and drop framework in android with a clean example. This process follows list of states sequentially as listed below,

1. Started
           This event occurs when we start dragging the object. System calls onStart() method to start the drag. As a call back system first displays drag shadow of the object(shown in screen shot below), then the system sends a drag event with action type ACTION_DRAG_STARTED to the drag event listeners.
             To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.
           
2. Continuing
            The user continues the drag and system sends ACTION_DRAG_ENTERED event.

3. Dropped
             The user releases the drag object and for which the system sends drag event with action type ACTION_DROP.

4. Ended
             Once after the system sends ACTION_DROPPED event, system will again send ACTION_DRAG_ENDED event to indicate that the drag operation is complete.

These are the phases in drag and drop example. All we need to do is, capture the events send by the system, obtain X and Y co-ordinates after drag completion and place the object in its desired co-ordinates.

Step 1: Place an image in Android layout
            UI layout is quite simple, just place and imageView android element and place your desired image here.

Step 2: Implement Drag and drop program
            Once the user performs long press to drag the object we need to copy and move the data along with shadow image as shown below , Here ClipData class is used to copy and paste the image in desired location.

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 DragShadowBuilder(img);
v.startDrag(dragData, myShadow, null, 0 );

After which, set setOnDragListener() on the image view hence we will start receiving events on image drag and drop. Capture the X and Y co-ordinates of the image on ACTION_DRAG_ENDED event and locate the image in final location. Switch through the events and code appropriate functions for the events as shown below:

MainActivity.java

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.util.Log;
import android.widget.RelativeLayout.LayoutParams;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnDragListener;
import android.widget.*;

public class MainActivity extends Activity {
private static final String IMAGEVIEW_TAG = "Cte Logo";
String msg;
ImageView img;
private LayoutParams layoutParams;

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

img = (ImageView) findViewById(R.id.imgView);
// Sets the tag
img.setTag(IMAGEVIEW_TAG);
// Sets a long click listener for the 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);

// Instantiates the drag shadow builder.
View.DragShadowBuilder myShadow = new DragShadowBuilder(img);

// Starts the drag
v.startDrag(dragData, // the data to be dragged
myShadow, // the drag shadow builder
null, // no need to use local data
0 // flags (not currently used, set to 0)
);
return true;
}
});

// Set the drag event listener for the View
img.setOnDragListener(new OnDragListener() {
@SuppressLint("NewApi")
@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");
break;
case DragEvent.ACTION_DRAG_ENTERED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
int x = (int) event.getX();
int y = (int) event.getY();
break;
case DragEvent.ACTION_DRAG_EXITED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
x = (int) event.getX();
y = (int) event.getY();
layoutParams.leftMargin = x;
layoutParams.topMargin = y;
v.setLayoutParams(layoutParams);
break;
case DragEvent.ACTION_DRAG_LOCATION:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
x = (int) event.getX();
y = (int) event.getY();
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");

break;
case DragEvent.ACTION_DROP:
Log.d(msg, "ACTION_DROP event");

break;
default:
break;
}
return true;
}
});
}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:src="@drawable/cte" />


</RelativeLayout>

That's it.. We are done with drag and drop example in android.. Check out the program output and screenshots below..

Image Before Drag

Drag object Shadow

Image after drag


Source Code of the application
AndroidDragandDrop.zip





Reactions:

1 comment :

  1. it just move from top to bottom.
    but, what if I want the image can move to all direction?

    ReplyDelete