Build apps faster with our new App builder! Check it out →

dragAndDropTarget

Common

Modifier in Compose Foundation

A modifier that allows for receiving from a drag and drop gesture.

Last updated:

Installation

dependencies {
   implementation("androidx.compose.foundation:foundation:1.8.0-alpha04")
}

Overloads


fun Modifier.dragAndDropTarget(
    shouldStartDragAndDrop: (startEvent: DragAndDropEvent) -> Boolean,
    target: DragAndDropTarget,
): Modifier

Parameters

namedescription
shouldStartDragAndDropAllows the Composable to decide if it wants to receive from a given drag and drop session by inspecting the [DragAndDropEvent] that started the session.
targetThe [DragAndDropTarget] that will receive events for a given drag and drop session.

Code Example

TextDragAndDropTargetSample

@Composable
fun TextDragAndDropTargetSample(
    eventSummary: String?,
    onDragAndDropEventDropped: (DragAndDropEvent) -> Unit,
) {
    val validMimeTypePrefixes = remember {
        setOf(
            ClipDescription.MIMETYPE_TEXT_INTENT,
            "image/",
            "text/",
            "video/",
            "audio/",
        )
    }
    var backgroundColor by remember { mutableStateOf(Color.Transparent) }
    val dragAndDropTarget = remember {
        object : DragAndDropTarget {
            override fun onStarted(event: DragAndDropEvent) {
                backgroundColor = Color.DarkGray.copy(alpha = 0.2f)
            }

            override fun onDrop(event: DragAndDropEvent): Boolean {
                onDragAndDropEventDropped(event)
                return true
            }

            override fun onEnded(event: DragAndDropEvent) {
                backgroundColor = Color.Transparent
            }
        }
    }
    Box(
        modifier =
            Modifier.fillMaxSize()
                .dragAndDropTarget(
                    shouldStartDragAndDrop = accept@{ startEvent ->
                            val hasValidMimeType =
                                startEvent.mimeTypes().any { eventMimeType ->
                                    validMimeTypePrefixes.any(eventMimeType::startsWith)
                                }
                            hasValidMimeType
                        },
                    target = dragAndDropTarget,
                )
                .background(backgroundColor)
                .border(width = 4.dp, color = Color.Magenta, shape = RoundedCornerShape(16.dp)),
    ) {
        when (eventSummary) {
            null -> Text(modifier = Modifier.align(Alignment.Center), text = "Drop anything here")
            else ->
                Text(
                    modifier =
                        Modifier.padding(horizontal = 16.dp, vertical = 24.dp)
                            .verticalScroll(rememberScrollState()),
                    text = eventSummary
                )
        }
    }
}
by @alexstyl