This
tutorial speaks about Drag and Drop capability of android applications and categorized under Android user
interface.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 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
- Design Layout: Design layout
that contains two or more bounding spaces and the view to be dragged.
- Create Activity: Create
activity which implements required listener classes.
- 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
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
Comments
Post a Comment