實作 View 的拖曳功能

您可以回應可能會觸發拖曳開始及回應放置事件的事件,在檢視畫面中實作拖曳程序。

開始拖曳

使用者以手勢開始拖曳,通常可透過輕觸或按住要拖曳的項目來完成。

如要在 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 先前回報可接受拖曳的內容時,系統就會將拖曳事件分派給動作類型為 ACTION_DROPView

拖曳事件監聽器必須執行下列操作:

  1. 呼叫 getClipData() 以取得原先在呼叫 startDragAndDrop() 中提供的 ClipData 物件,並處理資料。如果拖曳作業不是資料移動,就不需要進行這項步驟。

  2. 回傳布林值 true,表示已成功處理放置;如未成功處理,則回傳 false。回傳的值會成為 getResult() 最終為 ACTION_DRAG_ENDED 事件回傳的值。如果系統未傳送 ACTION_DROP 事件,則 getResult()ACTION_DRAG_ENDED 事件回傳的值會是 false

如果是 ACTION_DROP 事件,getX()getY() 會使用接收放置的 View 座標系統,在放置時回傳觸控點的 XY 位置。

使用者可在拖曳事件監聽器未接收拖曳事件的 View 上放開拖曳陰影、應用程式 UI 的空白區域,甚至是應用程式外的區域,Android 不會傳送動作類型為 ACTION_DROP 的事件,只會傳送 ACTION_DRAG_ENDED 事件。

回應拖曳結束事件

在使用者放開拖曳陰影後,系統會立即將動作類型為 ACTION_DRAG_ENDED 的拖曳事件傳送至應用程式中的所有拖曳事件監聽器。這表示拖曳作業已完成。

每個拖曳事件監聽器都必須執行下列操作:

  1. 假如事件監聽器在作業期間變更外觀,則應將其重設為預設外觀,讓使用者瞭解作業已完成。
  2. 事件監聽器可以選擇呼叫 getResult() 以進一步瞭解作業。如果事件監聽器回傳 true 以回應動作類型 ACTION_DROP 的事件,則 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);
    }
}