androidandroid-jetpack-composedrag

How to make dragged item follow pointer position without latency in Android JetPack Compose?


I have a draggable item using the detectDragGestures function. However, I've noticed that when the user presses the screen and makes quick movements, there is a noticeable latency between the original pointer movement and the corresponding movement of the dragged item on the screen.

Dragging with latency

Here's the code snippet which I took from the official documentation:

@Composable
fun DraggableTextLowLevel() {
    Box(modifier = Modifier.fillMaxSize()) {
        var offsetX by remember { mutableStateOf(0f) }
        var offsetY by remember { mutableStateOf(0f) }

        Box(
            Modifier
                .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
                .background(Color.Blue)
                .size(50.dp)
                .pointerInput(Unit) {
                    detectDragGestures { change, dragAmount ->
                        change.consume()
                        offsetX += dragAmount.x
                        offsetY += dragAmount.y
                    }
                }
        )
    }
}

I want the dragged item to follow the pointer position without any delay.

What adjustments can I make to the code to achieve a more immediate drag behavior?

Any suggestions would be appreciated!


Solution

  • The code looks OK and when I try it the observed latency is much lower.

    That said, you can try the following:

    .draggable2D(rememberDraggable2DState {
        offsetX += it.x
        offsetY += it.y
    })