1
+ package com.example.compose.snippets.draganddrop
2
+
3
+ import android.content.ClipData
4
+ import android.content.ClipDescription
5
+ import android.os.Build
6
+ import android.view.View
7
+ import androidx.annotation.RequiresApi
8
+ import androidx.compose.foundation.ExperimentalFoundationApi
9
+ import androidx.compose.foundation.draganddrop.dragAndDropSource
10
+ import androidx.compose.foundation.draganddrop.dragAndDropTarget
11
+ import androidx.compose.foundation.gestures.detectTapGestures
12
+ import androidx.compose.runtime.Composable
13
+ import androidx.compose.runtime.remember
14
+ import androidx.compose.ui.Modifier
15
+ import androidx.compose.ui.draganddrop.DragAndDropEvent
16
+ import androidx.compose.ui.draganddrop.DragAndDropTarget
17
+ import androidx.compose.ui.draganddrop.DragAndDropTransferData
18
+ import androidx.compose.ui.draganddrop.mimeTypes
19
+
20
+ @RequiresApi(Build .VERSION_CODES .N )
21
+ @OptIn(ExperimentalFoundationApi ::class )
22
+ @Composable
23
+ fun DragAndDropSnippet () {
24
+
25
+ val url = " "
26
+
27
+ // [START android_compose_drag_and_drop_1]
28
+ Modifier .dragAndDropSource {
29
+ detectTapGestures(onLongPress = {
30
+ startTransfer(
31
+ DragAndDropTransferData (
32
+ ClipData .newPlainText(
33
+ " image Url" , url
34
+ )
35
+ )
36
+ )
37
+ })
38
+ }
39
+ // [END android_compose_drag_and_drop_1]
40
+
41
+ // [START android_compose_drag_and_drop_2]
42
+ Modifier .dragAndDropSource {
43
+ detectTapGestures(onLongPress = {
44
+ startTransfer(
45
+ DragAndDropTransferData (
46
+ ClipData .newPlainText(
47
+ " image Url" , url
48
+ ), flags = View .DRAG_FLAG_GLOBAL
49
+ )
50
+ )
51
+ })
52
+ }
53
+ // [END android_compose_drag_and_drop_2]
54
+
55
+ // [START android_compose_drag_and_drop_3]
56
+ val callback = remember {
57
+ object : DragAndDropTarget {
58
+ override fun onDrop (event : DragAndDropEvent ): Boolean {
59
+ // Parse received data
60
+ return true
61
+ }
62
+ }
63
+ }
64
+ // [END android_compose_drag_and_drop_3]
65
+
66
+ // [START android_compose_drag_and_drop_4]
67
+ Modifier .dragAndDropTarget(
68
+ shouldStartDragAndDrop = { event ->
69
+ event.mimeTypes().contains(ClipDescription .MIMETYPE_TEXT_PLAIN )
70
+ }, target = callback
71
+ )
72
+ // [END android_compose_drag_and_drop_4]
73
+
74
+ // [START android_compose_drag_and_drop_5]
75
+ object : DragAndDropTarget {
76
+ override fun onStarted (event : DragAndDropEvent ) {
77
+ // When the drag event starts
78
+ }
79
+
80
+ override fun onEntered (event : DragAndDropEvent ) {
81
+ // When the dragged object enters the target surface
82
+ }
83
+
84
+ override fun onEnded (event : DragAndDropEvent ) {
85
+ // When the drag event stops
86
+ }
87
+
88
+ override fun onExited (event : DragAndDropEvent ) {
89
+ // When the dragged object exits the target surface
90
+ }
91
+
92
+ override fun onDrop (event : DragAndDropEvent ): Boolean = true
93
+ }
94
+ // [END android_compose_drag_and_drop_5]
95
+ }
0 commit comments