Cómo implementar la función de arrastrar y soltar con vistas

Puedes implementar el proceso de arrastrar y soltar en vistas si respondes a eventos que podrían activar un inicio de arrastre y respondes y consumes eventos de soltar.

Inicia un arrastre

El usuario inicia un arrastre con un gesto, por lo general, tocando o haciendo clic y manteniendo presionado un elemento que quiere arrastrar.

Para controlar esto en una View, crea un objeto ClipData y un objeto ClipData.Item para los datos que se moverán. Como parte de ClipData, proporciona metadatos que se almacenen en un objeto ClipDescription dentro de ClipData. Para una operación de arrastrar y soltar que no represente movimiento de datos, te recomendamos que uses null en lugar de un objeto real.

Por ejemplo, en este fragmento de código, se muestra cómo responder a un gesto de mantener presionado en un ImageView creando un objeto ClipData que contiene la etiqueta de un 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;
});

Responde a un inicio de arrastre

Durante la operación de arrastre, el sistema despacha eventos de arrastre a los objetos de escucha de eventos de arrastre de los objetos View del diseño actual. Los objetos de escucha reaccionan llamando a DragEvent.getAction() para obtener el tipo de acción. Cuando se inicia un arrastre, este método muestra ACTION_DRAG_STARTED.

En respuesta a un evento con el tipo de acción ACTION_DRAG_STARTED, un objeto de escucha de eventos de arrastre debe hacer lo siguiente:

  1. Llama a DragEvent.getClipDescription() y usa los métodos de tipo de MIME en el objeto ClipDescription que se muestra para ver si el objeto de escucha puede aceptar los datos que se arrastran.

    Si la operación de arrastrar y soltar no representa movimiento de datos, es posible que esto no sea necesario.

  2. Si el objeto de escucha de eventos de arrastre puede aceptar la acción de soltar, debe mostrar true para indicarle al sistema que siga enviando eventos de arrastre al objeto de escucha. Si el objeto de escucha no puede aceptar la acción de soltar, debe mostrar false, y el sistema deja de enviar eventos de arrastre hasta que envíe ACTION_DRAG_ENDED para concluir la operación de arrastrar y soltar.

Para un evento ACTION_DRAG_STARTED, los siguientes métodos DragEvent no son válidos: getClipData(), getX(), getY() y getResult().

Controla eventos durante el arrastre

Durante la acción de arrastre, los objetos de escucha de eventos de arrastre que muestran true en respuesta al evento de arrastre ACTION_DRAG_STARTED continúan recibiendo eventos de arrastre. Los tipos de eventos de arrastre que recibe un objeto de escucha durante el arrastre dependen de la ubicación de la sombra de arrastre y de la visibilidad del View del objeto de escucha. Los objetos de escucha usan los eventos de arrastre principalmente para decidir si deben cambiar el aspecto de su View.

Durante el arrastre, DragEvent.getAction() muestra uno de tres valores:

  • ACTION_DRAG_ENTERED: El objeto de escucha recibe este tipo de acción de evento cuando el punto táctil (el punto en la pantalla debajo del dedo o mouse del usuario) ingresa al cuadro de límite del elemento View del objeto de escucha.
  • ACTION_DRAG_LOCATION: Una vez que el objeto de escucha recibe un evento ACTION_DRAG_ENTERED, recibe un evento ACTION_DRAG_LOCATION nuevo cada vez que se mueve el punto táctil hasta que recibe un evento ACTION_DRAG_EXITED. Los métodos getX() y getY() muestran las coordenadas X e Y del punto táctil.
  • ACTION_DRAG_EXITED: Este tipo de acción de evento se envía a un objeto de escucha que recibe ACTION_DRAG_ENTERED. El evento se envía cuando el punto táctil de la sombra de arrastre se mueve desde el cuadro de límite del elemento View del objeto de escucha hacia afuera del cuadro de límite.

El objeto de escucha de eventos de arrastre no necesita reaccionar a ninguno de estos tipos de acciones. Si el objeto de escucha muestra un valor al sistema, se ignora.

A continuación, se describen algunas pautas para responder a cada uno de estos tipos de acción:

  • En respuesta a ACTION_DRAG_ENTERED o ACTION_DRAG_LOCATION, el objeto de escucha puede cambiar el aspecto de View a fin de indicar que la vista es un posible destino de la acción de soltar.
  • Un evento con el tipo de acción ACTION_DRAG_LOCATION contiene datos válidos para getX() y getY() que corresponden a la ubicación del punto táctil. El objeto de escucha puede usar esta información para modificar el aspecto de View en el punto táctil o determinar la posición exacta en la que el usuario puede soltar el contenido.
  • En respuesta a ACTION_DRAG_EXITED, el objeto de escucha debe restablecer cualquier cambio de aspecto que se aplique en respuesta a ACTION_DRAG_ENTERED o ACTION_DRAG_LOCATION. Esto le indica al usuario que el elemento View ya no es un destino inminente de la acción de soltar.

Responde a la acción de soltar

Cuando el usuario suelta la sombra de arrastre sobre una View y el View informa anteriormente que puede aceptar el contenido que se arrastra, el sistema envía un evento de arrastre al View con el tipo de acción ACTION_DROP.

El objeto de escucha de eventos de arrastre debe hacer lo siguiente:

  1. Llama a getClipData() para obtener el objeto ClipData que se suministró originalmente en la llamada a startDragAndDrop() y procesa los datos. Si la operación de arrastrar y soltar no representa movimiento de datos, esto no es necesario.

  2. Muestra un booleano true para indicar que la acción de soltar se procesa correctamente o false si no lo es. El valor mostrado se convierte en el valor que getResult() muestra para el evento ACTION_DRAG_ENDED final. Si el sistema no envía un evento ACTION_DROP, el valor que muestra getResult() para un evento ACTION_DRAG_ENDED es false.

En el caso de un evento ACTION_DROP, getX() y getY() usan el sistema de coordenadas de View que recibe la bajada para mostrar la posición X e Y del punto táctil en el momento de la caída.

Si bien el usuario puede liberar la sombra de arrastre sobre un View cuyo objeto de escucha de eventos de arrastre no recibe eventos de arrastre, regiones vacías de la IU de tu app o incluso sobre áreas fuera de la aplicación, Android no enviará un evento con el tipo de acción ACTION_DROP y solo enviará un evento ACTION_DRAG_ENDED.

Responde a la finalización de un arrastre

Inmediatamente después de que el usuario suelta la sombra de arrastre, el sistema envía un evento de arrastre con un tipo de acción ACTION_DRAG_ENDED a todos los objetos de escucha de eventos de arrastre de tu aplicación. Esto indica que finalizó la operación de arrastre.

Cada objeto de escucha de eventos de arrastre debe hacer lo siguiente:

  1. Si el objeto de escucha cambia su apariencia durante la operación, debe restablecerse a su aspecto predeterminado como una indicación visual para el usuario de que finalizó la operación.
  2. De manera optativa, el objeto de escucha puede llamar a getResult() para obtener más información sobre la operación. Si un objeto de escucha muestra true en respuesta a un evento del tipo de acción ACTION_DROP, getResult() muestra un valor booleano true. En todos los demás casos, getResult() muestra un valor booleano false, incluso cuando el sistema no envía un evento ACTION_DROP.
  3. Para indicar que la operación de soltar se completó correctamente, el objeto de escucha debe mostrar un valor booleano true al sistema. Si no se muestra false, una indicación visual que muestra la sombra paralela que regresa a su fuente puede sugerirle al usuario que la operación no se realizó correctamente.

Cómo responder a eventos de arrastre: ejemplo

Todos los eventos de arrastre son recibidos inicialmente por el objeto de escucha o el método de evento de arrastre. El siguiente fragmento de código es un ejemplo de respuesta a eventos de arrastre:

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;

});

Cómo personalizar una sombra de arrastre

Puedes definir un myDragShadowBuilder personalizado si anulas los métodos de View.DragShadowBuilder. En el siguiente fragmento de código, se crea una pequeña sombra de arrastre gris rectangular y gris para un 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);
    }
}