1. The introduction

In the development, drag and drop is a relatively common gesture operation, using it can make the application interaction more convenient and friendly, this article will briefly introduce how to add drag and drop effect for the View in Android.

2. Introduction of main methods and classes

2.1 startDragAndDrop () and startDrag ()

To drag and drop a View, call the View’s startDragAndDrop() or startDrag() method. The startDragAndDrop() method requires API version 24 or above, and the View can be dragged.

//data: Data to be passed by the drag-and-drop operation
//shadowBuilder: Drag and drop shadows
//myLocalState: an object containing data related to drag-and-drop operations
//flags: flags that control drag and drop operations
public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,Object myLocalState, int flags)
Copy the code

2.2 setOnDragListener ()

The View that receives the drag-drop event is called the target View for now. The target View calls setOnDragListener() and implements onDrag() to receive the drag-drop event callback.

2.3 the DragShadowBuilder

The view. DragShadowBuilder class provides a constructor that can pass in a View. This View is the View that is being dragged. This will be passed as an argument to the startDragAndDrop() or startDrag() methods, and can be inherited from the View.DragShadowBuilder class if necessary to achieve a custom effect.

2.4 DragEvent

This class mainly defines the types of drag-and-drop events. Different event types can be obtained from event.getAction().

// dragEvent. ACTION_DRAG_STARTED: Indicates that the drag has started
// dragEvent. ACTION_DRAG_ENTERED: Drag the shadow into the target View
// dragEvent. ACTION_DRAG_LOCATION: Responds to this event multiple times when dragging the shadow within the target View boundary
// dragEvent. ACTION_DRAG_EXITED: drags the shadow away from the target View boundary
// dragEvent. ACTION_DROP: The drag shadow is released
// dragevent.action_drag_ended: Indicates that the drag-and-drop operation is about to end. In this case, you need to call the return value of event.getresult () to determine whether the drag-and-drop operation is successful
Copy the code

3. Demonstrate drag and drop an image into the box

To illustrate the general flow of the drag-and-drop operation, we now demonstrate dragging and dropping an image into a box which is a LinearLayout with a box background.

3.1 Simple Layout

The layout is as follows:

<? xml version="1.0" encoding="utf-8"? > <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/iv_drag"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher" />

    <LinearLayout
        android:id="@+id/ll_accept"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="50dp"
        android:background="@drawable/black_bac"
        android:orientation="vertical">
    </LinearLayout>

</RelativeLayout>
Copy the code

3.2 Manipulate the picture to be dragged and dropped

Call setOnLongClickListener() to set up the event callback, then build ClipData and drag shadows, and then call startDragAndDrop() or startDrag() to drag.

iv_drag.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        CharSequence charSequence = (CharSequence) iv_drag.getTag();
        ClipData.Item item = new ClipData.Item(charSequence);
        ClipData clipData = new ClipData(charSequence, new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item);
        View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(iv_drag);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            iv_drag.startDragAndDrop(clipData, shadowBuilder, null.0);
        } else {
            iv_drag.startDrag(clipData, shadowBuilder, null.0);
        }
        return true; }});Copy the code

3.3 Boxes receive pictures

To receive the image, the target View calls setOnDragListener() to receive the drag-event callback, uses event.getAction() to get the different drag-event types, and then performs the appropriate actions based on the event type, as shown in the following example:

ll_accept.setOnDragListener(new View.OnDragListener() {
    @Override
    public boolean onDrag(View v, DragEvent event) {
        switch (event.getAction()) {
            case DragEvent.ACTION_DRAG_STARTED:
                iv_drag.setVisibility(View.GONE);
                if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                    return true;
                }
                return false;

            case DragEvent.ACTION_DRAG_ENTERED:
                isChangePos = true;
                ll_accept.setBackgroundResource(R.drawable.green_bac);
                return true;

            case DragEvent.ACTION_DRAG_LOCATION:
                x = event.getX();
                y = event.getY();
                return true;

            case DragEvent.ACTION_DRAG_EXITED:
                isChangePos = false;
                ll_accept.setBackgroundResource(R.drawable.black_bac);
                return true;

            case DragEvent.ACTION_DROP:

                return true;

            case DragEvent.ACTION_DRAG_ENDED:
                ll_accept.setBackgroundResource(R.drawable.black_bac);
                if (isChangePos && event.getResult()) {
                    int left = ll_accept.getLeft();
                    int top = ll_accept.getTop();
                    x = x + left - (iv_drag.getWidth() / 2);
                    y = y + top - (iv_drag.getHeight() / 2);
                    iv_drag.setX(x);
                    iv_drag.setY(y);
                }
                iv_drag.setVisibility(View.VISIBLE);
                return true;
        }
        return false; }});Copy the code

4. To summarize

In the process of development, we will use a variety of views to achieve drag and drop effects, mainly including drag shadow construction, drag and drop method invocation and the processing of drag and drop events, in the appropriate scene for View to add drag and drop effects can make the application interaction more convenient and friendly.