Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-compose-text

How to detect motion events on a compose button?


I am trying to create an icon button which invokes a lambda when tapped, but if the user presses the button and holds it, then also the lambda should get continuously invoked in fixed intervals.

@Composable
fun MyIconButton(
    someLambda: () -> Unit
) {
    IconButton(onClick = someLambda) {
        Icon(
            // painter and content description
        )
    }
}

Here what I want is that when user presses the button, someLambda should get invoked (which is working fine). Additionally, I also want to invoke someLambda repeatedly (with a gap of 500ms between two invocations) until the user releases the button.

Basically what I want is to detect something like the KeyUp and KeyDown events.

How to achieve this?


Solution

  • I solved the problem using this Modifier.pointerInput on my Icon.

    Modifier.pointerInput(true) {
        detectTapGestures(onPress = {
            coroutineScope {
                val job = launch {
                    while (true) {
                        // Invoke lambda
                        delay(500)
                    }
                }
                tryAwaitRelease()
                job.cancel()
            }
        })
    }
    

    As per the documentation,

    onPress is called when the press is detected and PressGestureScope.tryAwaitRelease can be used to detect when pointers have released or the gesture was canceled.