In Jetpack Compose, once the user places a finger down on a screen and moves it, I want to be notified of the finger position.
How can I track the finger movement?
CodePudding user response:
The mechanism for this is a Composable's Modifier pointerInput
value.
Surface(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
positionX = change.position.x
positionY = change.position.y
Log.d("location", "${change.position}")
}
}){
......
}
The pointerInput
has a variety of the gesture detectors you can specify to detect only certain types of gestures, which is very helpful. With the code above, I was able to allow the user to drag a circle around the screen.
CodePudding user response:
Modifier.pointerInput()
offers many options such as detecting tap gestures with long press, double tap, or drag gestures or transform gestures for detecting zoom, rotate, centroid change or pan motions.
However with drag gestures you are not able to detect initial down because it requires a threshold to be passed via for onDragStart to kick in.
You need to check out awaitFirstDown()
when first pointer is down then awaitPointerEvent()
in a loop for move events and end of loop for up event.
You can find my detailed answer about gestures here and how to build a basic drawing app using gestures is available in this answer.
Also parameter or parameters of Modifier.pointerInput(keys
) are very important to restart closure when you don't want to hold obsolete values.