Drag and drop gestures are no stranger to most desktop operations, such as dragging files to the recycle bin. With the trend of large screens on mobile devices and the improvement of foldable devices, drag and drop operations in mobile platforms are becoming more necessary and popular!

Implement drag and drop gestures: Existing solutions on Android are slightly more complex. Based on this, DragAndDrop is a new member of the Jetpack framework collection.

This article focuses on the vision and core points of the framework, translated from Android Developer Relations EngineerPaulMeduimIn the Post:Simplifying drag and drop.

Essentially, drag and drop is when a user clicks to select an image, text, or other data element, then drags and drops it directly to another screen, or even another App’s screen, and the data is incorporated into the new screen. This gesture usually takes the form of a long drag on a touch screen or a click on a non-touch screen and a drag with the mouse, followed by a drop at the target position.

Take a look at a typical drag-and-drop effect in an App:

While Android has long supported drag-and-drop gestures (for example, the DragEvent API was added as early as Android 3.0), it has often proved difficult and complex to fully and smoothly integrate gestures, touch events, permissions, and callbacks into the process.

Now I’d like to introduce the newest members of JetpackDragAnd Drop frameworkAt presentalphaThis version is designed to make it easier for you to drag and drop data within your App.

Build. Gradle with a dependency and use it.

implementation 'androidx. Draganddrop: draganddrop: 1.0.0 - alpha02'
Copy the code

The use of drag-and-drop gestures is increasingly common on large-screen devices, such as tablets and laptops, especially foldable devices. Split-screen operations are up to seven times more common on these types of devices than on traditional smartphones. Their users often need to use the split screen or window (developer.android.com/guide/topic…). Mode to handle multitasking scenarios, and dragging and dropping data between different apps is a natural experience and need!

The Android platform already has native support for dragging text from the EditText input box control, but we strongly recommend that developers implement gestures for dragging data from other controls, including images, files, and other data types in addition to text. Of course, it’s equally important to reverse the support for dragging and dropping data from other apps, and should be encouraged.

Here’s an example of dragging and dropping text and images between apps:

DragStartHelper, in conjunction with DropHelper, forms the core API of the entire framework. They make it easy to implement gestures, data callbacks, styles, and pixel-level UI alignment.

DragStartHelper

As a utility class in the Core package of the Jetpack framework collection, DragStartHelper is responsible for monitoring the start of the drag gesture. These gestures include dragging, clicking and dragging with the mouse.

It’s easy to use, wrap in the view you want to listen on and start listening. The frame will call back when the drag gesture is triggered, and then do some simple configuration.

  1. Wrap the data that needs to be passed toClipData
  2. Create a new image instance to show the drag effectDragShadowBuilder
  3. Native method of handing data and drag effects plus some flags to a ViewstartDragAndDrop()Perform subsequent actions, including showing effects and transferring data
// Make a view draggable to share a file. DragStartHelper takes care of
// intercepting drag gestures and attaching the listener.
DragStartHelper(draggableView) { view, _ ->
    // Sets the appropriate MIME types automatically.
    val dragClipData = ClipData.newUri(contentResolver, "File", fileUri)

    // Set the visual look of the dragged object.
    // Can be extended and customized; we use the default here.
    val dragShadow = View.DragShadowBuilder(view)

    // Starts the drag. Note that the global flag allows for cross-app dragging.
    view.startDragAndDrop(
        dragClipData,
        dragShadow,
        null.// Optional extra local state information
        // Since this is a "content:" URI and not just plain text, we can use the
        // DRAG_FLAG_GLOBAL_URI_READ to allow other apps to read from our content
        // provider. Without it, other apps won't receive the drag events.
        DRAG_FLAG_GLOBAL or DRAG_FLAG_GLOBAL_URI_READ)
    )
}.attach()
Copy the code

DropHelper

Another core utility class, DropHelper, cares about the timing of dragging data down and the target view.

The code for adaptation is simple:

  1. An attempt call is required for drag-and-drop dataconfigureViewmethods
  2. It also needs to set the data type that it cares about internallyMime Type
  3. Specify some additional optional parameter instancesDropHelper.Options“For example, highlighted when put downcolorandScope of viewEtc.
  4. Finally, set the most important drop listenerOnReceiveContentListenerTo retrieve data from ClipData for upload, display, and of course, mismatched warnings or view alerts

Note: When building drophelper.options instances, call addInnerEditTexts() to ensure that nested EditText controls don’t rob view focus.

DropHelper.configureView(
    // Activity that will handle the drop
    this.// Target drop view to be highlighted
    outerDropTarget,
    // Supported MIME types
    arrayOf(MIMETYPE_TEXT_PLAIN, "image/*"),
    // Options for configuring drop targets
    DropHelper.Options.Builder()
        // To ensure proper drop target highlighting, all EditText elements in
        // the drop target view hierarchy must be included in a call to this
        // method. Otherwise, an EditText within the target, rather than the
        // target view itself, acquires focus during the drag and drop operation.
        .addInnerEditTexts(innerEditText)
        .build()
) { _, payload ->
  // Process the payload here, returning any content that should be delegated to
  // the platform.. }Copy the code

To learn more

The above is only a brief introduction. More details can be found in the following official documents:

  • Drag and drop gesture of official documentation: developer.android.com/guide/topic…

Of course, you can also learn and practice more deeply through the official complete DEMO:

  • Official DEMO address: github.com/android/use…

It’s also important to remember to give feedback on any bugs or comments you encounter on the Android Issue website:

  • Issuetracker.google.com/issues/new?…

Finally, if you find my explanation difficult to understand, read the original translation of this article:

  • Simplifying drag and drop