Kotlin Composable detectDragGestures Output On Drop Position?

Viewed 482

I have a Kotlin jetpack composable box item that I set to be able to click and drag. It outputs all the real time coordinates of the box, but is there a way to output only the last value the moment I lift my fingers and dropping the box?

@Composable
fun createDragImage(){
    MaterialTheme{
        val count = remember { mutableStateOf(0) }
        val context = LocalContext.current

        Row(
            modifier = Modifier
                .padding(20.dp)
                .border(border = BorderStroke(width = 1.dp, color = Color.Red)),
            verticalAlignment = Alignment.CenterVertically,

        ) {

            Box() {
                var offsetX by remember { mutableStateOf(0f) }
                var offsetY by remember { mutableStateOf(0f) }

                Box(
                    Modifier
                        .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
                        .background(Color.Transparent)
                        .size(150.dp)
                        .border(BorderStroke(4.dp, SolidColor(Color.Red)))
                        .pointerInput(Unit) {
                            detectDragGestures { change, dragAmount ->
                                change.consumeAllChanges()
                                
                                offsetX = box1.toFloat() 
                                offsetY += dragAmount.y

                            }
                        }
                )
                
            }
1 Answers

You can use the onDragEnd parameter.
Something like:

        var offsetX by remember { mutableStateOf(0f) }
        var offsetY by remember { mutableStateOf(0f) }
        var offsetDraggingX by remember { mutableStateOf(0f) }
        var offsetDraggingY by remember { mutableStateOf(0f) }

        Box(
            Modifier
                .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
                .pointerInput(Unit) {
                    detectDragGestures(
                        onDragEnd = {
                            offsetX =  offsetDraggingX
                            offsetY =  offsetDraggingY
                        }
                    ) { change, dragAmount ->
                        //change.consumeAllChanges()

                        offsetDraggingX += dragAmount.x
                        offsetDraggingY += dragAmount.y

                    }
                }

        )
Related