使用视图实现拖放

您可以在视图中实现拖放流程,方法是响应可能会触发拖动开始的事件,并响应并使用放下事件。

开始拖动

用户使用手势开始拖动,通常是通过触摸或点击并按住想要拖动的项。

如需在 View 中处理此操作,请为要移动的数据创建 ClipData 对象和 ClipData.Item 对象。作为 ClipData 的一部分,请提供存储在 ClipData 内的 ClipDescription 对象中的元数据。对于不表示数据移动的拖放操作,您可能需要使用 null,而非实际对象。

例如,以下代码段展示了,如何通过创建包含 ImageView 的标记(或标签)的 ClipData 对象,来响应 ImageView 上的轻触并按住手势:

Kotlin

// Create a string for the ImageView label.
val IMAGEVIEW_TAG = "icon bitmap"
...
val imageView = ImageView(context).apply {
    // Set the bitmap for the ImageView from an icon bitmap defined elsewhere.
    setImageBitmap(iconBitmap)
    tag = IMAGEVIEW_TAG
    setOnLongClickListener { v ->
        // Create a new ClipData. This is done in two steps to provide
        // clarity. The convenience method ClipData.newPlainText() can
        // create a plain text ClipData in one step.

        // Create a new ClipData.Item from the ImageView object's tag.
        val item = ClipData.Item(v.tag as? CharSequence)

        // Create a new ClipData using the tag as a label, the plain text
        // MIME type, and the already-created item. This creates a new
        // ClipDescription object within the ClipData and sets its MIME type
        // to "text/plain".
        val dragData = ClipData(
            v.tag as? CharSequence,
            arrayOf(ClipDescription.MIMETYPE_TEXT_PLAIN),
            item)

        // Instantiate the drag shadow builder. We use this imageView object
        // to create the default builder.
        val myShadow = View.DragShadowBuilder(view: this)

        // Start the drag.
        v.startDragAndDrop(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.
        )

        // Indicate that the long-click is handled.
        true
    }
}

Java

// Create a string for the ImageView label.
private static final String IMAGEVIEW_TAG = "icon bitmap";
...
// Create a new ImageView.
ImageView imageView = new ImageView(context);

// Set the bitmap for the ImageView from an icon bitmap defined elsewhere.
imageView.setImageBitmap(iconBitmap);

// Set the tag.
imageView.setTag(IMAGEVIEW_TAG);

// Set a long-click listener for the ImageView using an anonymous listener
// object that implements the OnLongClickListener interface.
imageView.setOnLongClickListener( v -> {

    // Create a new ClipData. This is done in two steps to provide clarity. The
    // convenience method ClipData.newPlainText() can create a plain text
    // ClipData in one step.

    // Create a new ClipData.Item from the ImageView object's tag.
    ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());

    // Create a new ClipData using the tag as a label, the plain text MIME type,
    // and the already-created item. This creates a new ClipDescription object
    // within the ClipData and sets its MIME type to "text/plain".
    ClipData dragData = new ClipData(
            (CharSequence) v.getTag(),
            new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN },
            item);

    // Instantiate the drag shadow builder. We use this imageView object
    // to create the default builder.
    View.DragShadowBuilder myShadow = new View.DragShadowBuilder(imageView);

    // Start the drag.
    v.startDragAndDrop(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.
    );

    // Indicate that the long-click is handled.
    return true;
});

响应拖动开始事件

在拖动操作期间,系统会向当前布局中 View 对象的拖动事件监听器发送拖动事件。监听器会通过调用 DragEvent.getAction() 做出反应,以获取操作类型。拖动开始时,此方法会返回 ACTION_DRAG_STARTED

为了响应操作类型为 ACTION_DRAG_STARTED 的事件,拖动事件监听器必须执行以下操作:

  1. 调用 DragEvent.getClipDescription() 并使用返回的 ClipDescription 中的 MIME 类型方法,查看监听器能否接受正在拖动的数据。

    如果拖放操作不表示数据移动,则可能没必要这样做。

  2. 如果拖动事件监听器可以接受放下事件,则必须返回 true,以告知系统继续向该监听器发送拖动事件。如果监听器无法接受放下操作,则该监听器必须返回 false,并且系统会停止向该监听器发送拖动事件,直到系统发送 ACTION_DRAG_ENDED 结束拖放操作为止。

对于 ACTION_DRAG_STARTED 事件,以下 DragEvent 方法无效:getClipData()getX()getY()getResult()

在拖动期间处理事件

在拖动操作期间,返回 true 以响应 ACTION_DRAG_STARTED 拖动事件的拖动事件监听器会继续接收拖动事件。监听器在拖动期间收到的拖动事件类型取决于拖动阴影的位置和监听器的 View 的可见性。监听器主要使用拖动事件来确定是否必须更改其 View 的外观。

在拖动操作期间,DragEvent.getAction() 会返回以下三个值之一:

  • ACTION_DRAG_ENTERED:当接触点(用户手指或鼠标位于屏幕上的点)进入监听器的 View 的边界框时,监听器会收到此事件操作类型。
  • ACTION_DRAG_LOCATION:监听器收到 ACTION_DRAG_ENTERED 事件后,每当接触点移动时都会收到新的 ACTION_DRAG_LOCATION 事件,直到收到 ACTION_DRAG_EXITED 事件。getX()getY() 方法会返回接触点的 X 和 Y 坐标。
  • ACTION_DRAG_EXITED:系统会将此事件操作类型发送到先前接收 ACTION_DRAG_ENTERED 的监听器。当拖动阴影的接触点从监听器的 View 的边界框内移到边界框外时,系统会发送该事件。

拖动事件监听器无需对以上任何操作类型做出反应。如果监听器向系统返回值,该值将被忽略。

以下是响应以上各种操作类型的一些准则:

  • 在响应 ACTION_DRAG_ENTEREDACTION_DRAG_LOCATION 时,监听器可更改 View 的外观,以表明该视图是可能的拖放目标。
  • 操作类型为 ACTION_DRAG_LOCATION 的事件包含对应于接触点位置的 getX()getY() 的有效数据。监听器可以使用这些信息来更改 View 在接触点处的外观,或确定用户可以将内容放置到的确切位置。
  • 在响应 ACTION_DRAG_EXITED 时,监听器必须重置其在响应 ACTION_DRAG_ENTEREDACTION_DRAG_LOCATION 时应用的任何外观更改。以便向用户表明,View 已不再是当下的拖放目标。

响应放下事件

当用户将拖动阴影释放到 View 上,并且 View 之前报告它可以接受所拖动的内容时,系统会向 View 发送操作类型为 ACTION_DROP 的拖动事件。

拖动事件监听器必须执行以下操作:

  1. 调用 getClipData() 以获取最初在 startDragAndDrop() 调用中提供的 ClipData 对象并处理数据。如果拖放操作不表示数据移动,则没有必要这样做。

  2. 返回布尔值 true,表示已成功处理放下操作,如果处理失败,则返回 false。返回的值将成为 getResult() 针对最终 ACTION_DRAG_ENDED 事件返回的值。如果系统未发出 ACTION_DROP 事件,则 getResult() 针对 ACTION_DRAG_ENDED 事件返回的值为 false

对于 ACTION_DROP 事件,getX()getY() 会使用接收放下事件的 View 坐标系,以返回接触点在放下时刻的 X 和 Y 位置。

尽管用户能够将拖动阴影释放到其拖动事件监听器未接收拖动事件的 View 上、应用界面的空白区域,甚至是应用以外的区域,Android 不会发送操作类型为 ACTION_DROP 的事件,而只会发送 ACTION_DRAG_ENDED 事件。

响应拖动结束事件

当用户释放拖动阴影后,系统会立即向应用中的所有拖动事件监听器发送操作类型为 ACTION_DRAG_ENDED 的拖动事件。此事件表示拖动操作已完成。

每个拖动事件监听器都必须执行以下操作:

  1. 如果监听器在操作期间更改了外观,则应重置为默认外观,以视觉指示让用户了解操作已完成。
  2. 监听器可以选择调用 getResult(),以了解关于该操作的更多信息。如果监听器在响应操作类型为 ACTION_DROP 的事件时返回 true,则 getResult() 会返回布尔值 true。在所有其他情况下,getResult() 会返回布尔值 false,包括系统未发送 ACTION_DROP 事件的情况。
  3. 为了指示放下操作成功完成,监听器应向系统返回布尔值 true。如果不返回 false,一条指示阴影返回其来源的可视化提示可能会向用户表明操作失败。

响应拖动事件:示例

所有拖动事件均由拖动事件方法或监听器接收。以下代码段是响应拖动事件的示例:

Kotlin

val imageView = ImageView(this)

// Set the drag event listener for the View.
imageView.setOnDragListener { v, e ->

    // Handle each of the expected events.
    when (e.action) {
        DragEvent.ACTION_DRAG_STARTED -> {
            // Determine whether this View can accept the dragged data.
            if (e.clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                // As an example, apply a blue color tint to the View to
                // indicate that it can accept data.
                (v as? ImageView)?.setColorFilter(Color.BLUE)

                // Invalidate the view to force a redraw in the new tint.
                v.invalidate()

                // Return true to indicate that the View can accept the dragged
                // data.
                true
            } else {
                // Return false to indicate that, during the current drag and
                // drop operation, this View doesn't receive events again until
                // ACTION_DRAG_ENDED is sent.
                false
            }
        }
        DragEvent.ACTION_DRAG_ENTERED -> {
            // Apply a green tint to the View.
            (v as? ImageView)?.setColorFilter(Color.GREEN)

            // Invalidate the view to force a redraw in the new tint.
            v.invalidate()

            // Return true. The value is ignored.
            true
        }

        DragEvent.ACTION_DRAG_LOCATION ->
            // Ignore the event.
            true
        DragEvent.ACTION_DRAG_EXITED -> {
            // Reset the color tint to blue.
            (v as? ImageView)?.setColorFilter(Color.BLUE)

            // Invalidate the view to force a redraw in the new tint.
            v.invalidate()

            // Return true. The value is ignored.
            true
        }
        DragEvent.ACTION_DROP -> {
            // Get the item containing the dragged data.
            val item: ClipData.Item = e.clipData.getItemAt(0)

            // Get the text data from the item.
            val dragData = item.text

            // Display a message containing the dragged data.
            Toast.makeText(this, "Dragged data is $dragData", Toast.LENGTH_LONG).show()

            // Turn off color tints.
            (v as? ImageView)?.clearColorFilter()

            // Invalidate the view to force a redraw.
            v.invalidate()

            // Return true. DragEvent.getResult() returns true.
            true
        }

        DragEvent.ACTION_DRAG_ENDED -> {
            // Turn off color tinting.
            (v as? ImageView)?.clearColorFilter()

            // Invalidate the view to force a redraw.
            v.invalidate()

            // Do a getResult() and display what happens.
            when(e.result) {
                true ->
                    Toast.makeText(this, "The drop was handled.", Toast.LENGTH_LONG)
                else ->
                    Toast.makeText(this, "The drop didn't work.", Toast.LENGTH_LONG)
            }.show()

            // Return true. The value is ignored.
            true
        }
        else -> {
            // An unknown action type is received.
            Log.e("DragDrop Example", "Unknown action type received by View.OnDragListener.")
            false
        }
    }
}

Java

View imageView = new ImageView(this);

// Set the drag event listener for the View.
imageView.setOnDragListener( (v, e) -> {

    // Handle each of the expected events.
    switch(e.getAction()) {

        case DragEvent.ACTION_DRAG_STARTED:

            // Determine whether this View can accept the dragged data.
            if (e.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {

                // As an example, apply a blue color tint to the View to
                // indicate that it can accept data.
                ((ImageView)v).setColorFilter(Color.BLUE);

                // Invalidate the view to force a redraw in the new tint.
                v.invalidate();

                // Return true to indicate that the View can accept the dragged
                // data.
                return true;

            }

            // Return false to indicate that, during the current drag-and-drop
            // operation, this View doesn't receive events again until
            // ACTION_DRAG_ENDED is sent.
            return false;

        case DragEvent.ACTION_DRAG_ENTERED:

            // Apply a green tint to the View.
            ((ImageView)v).setColorFilter(Color.GREEN);

            // Invalidate the view to force a redraw in the new tint.
            v.invalidate();

            // Return true. The value is ignored.
            return true;

        case DragEvent.ACTION_DRAG_LOCATION:

            // Ignore the event.
            return true;

        case DragEvent.ACTION_DRAG_EXITED:

            // Reset the color tint to blue.
            ((ImageView)v).setColorFilter(Color.BLUE);

            // Invalidate the view to force a redraw in the new tint.
            v.invalidate();

            // Return true. The value is ignored.
            return true;

        case DragEvent.ACTION_DROP:

            // Get the item containing the dragged data.
            ClipData.Item item = e.getClipData().getItemAt(0);

            // Get the text data from the item.
            CharSequence dragData = item.getText();

            // Display a message containing the dragged data.
            Toast.makeText(this, "Dragged data is " + dragData, Toast.LENGTH_LONG).show();

            // Turn off color tints.
            ((ImageView)v).clearColorFilter();

            // Invalidate the view to force a redraw.
            v.invalidate();

            // Return true. DragEvent.getResult() returns true.
            return true;

        case DragEvent.ACTION_DRAG_ENDED:

            // Turn off color tinting.
            ((ImageView)v).clearColorFilter();

            // Invalidate the view to force a redraw.
            v.invalidate();

            // Do a getResult() and displays what happens.
            if (e.getResult()) {
                Toast.makeText(this, "The drop was handled.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "The drop didn't work.", Toast.LENGTH_LONG).show();
            }

            // Return true. The value is ignored.
            return true;

        // An unknown action type is received.
        default:
            Log.e("DragDrop Example","Unknown action type received by View.OnDragListener.");
            break;
    }

    return false;

});

自定义拖动阴影

您可以通过替换 View.DragShadowBuilder 中的方法来定义自定义 myDragShadowBuilder。以下代码段会为 TextView 创建一个较小的矩形灰色拖动阴影:

Kotlin

private class MyDragShadowBuilder(view: View) : View.DragShadowBuilder(view) {

    private val shadow = ColorDrawable(Color.LTGRAY)

    // Define a callback that sends the drag shadow dimensions and touch point
    // back to the system.
    override fun onProvideShadowMetrics(size: Point, touch: Point) {

            // Set the width of the shadow to half the width of the original
            // View.
            val width: Int = view.width / 2

            // Set the height of the shadow to half the height of the original
            // View.
            val height: Int = view.height / 2

            // The drag shadow is a ColorDrawable. Set its dimensions to
            // be the same as the Canvas that the system provides. As a result,
            // the drag shadow fills the Canvas.
            shadow.setBounds(0, 0, width, height)

            // Set the size parameter's width and height values. These get back
            // to the system through the size parameter.
            size.set(width, height)

            // Set the touch point's position to be in the middle of the drag
            // shadow.
            touch.set(width / 2, height / 2)
    }

    // Define a callback that draws the drag shadow in a Canvas that the system
    // constructs from the dimensions passed to onProvideShadowMetrics().
    override fun onDrawShadow(canvas: Canvas) {

            // Draw the ColorDrawable on the Canvas passed in from the system.
            shadow.draw(canvas)
    }
}

Java

private static class MyDragShadowBuilder extends View.DragShadowBuilder {

    // The drag shadow image, defined as a drawable object.
    private static Drawable shadow;

    // Constructor.
    public MyDragShadowBuilder(View view) {

            // Store the View parameter.
            super(view);

            // Create a draggable image that fills the Canvas provided by the
            // system.
            shadow = new ColorDrawable(Color.LTGRAY);
    }

    // Define a callback that sends the drag shadow dimensions and touch point
    // back to the system.
    @Override
    public void onProvideShadowMetrics (Point size, Point touch) {

            // Define local variables.
            int width, height;

            // Set the width of the shadow to half the width of the original
            // View.
            width = getView().getWidth() / 2;

            // Set the height of the shadow to half the height of the original
            // View.
            height = getView().getHeight() / 2;

            // The drag shadow is a ColorDrawable. Set its dimensions to
            // be the same as the Canvas that the system provides. As a result,
            // the drag shadow fills the Canvas.
            shadow.setBounds(0, 0, width, height);

            // Set the size parameter's width and height values. These get back
            // to the system through the size parameter.
            size.set(width, height);

            // Set the touch point's position to be in the middle of the drag
            // shadow.
            touch.set(width / 2, height / 2);
    }

    // Define a callback that draws the drag shadow in a Canvas that the system
    // constructs from the dimensions passed to onProvideShadowMetrics().
    @Override
    public void onDrawShadow(Canvas canvas) {

            // Draw the ColorDrawable on the Canvas passed in from the system.
            shadow.draw(canvas);
    }
}