onPressIn and onPressOut in jetpack compose

2.6k Views Asked by At

I have button to record voice so I want it to start record when user press it and stop when he leave it

@Composable
fun Screen(){
   
   Button(){
      Text("record")
   }

}
2

There are 2 best solutions below

2
On

To get the press/release actions in a Button you can use the InteractionSource.collectIsPressedAsState to know if the Button is pressed.
You can add a side effect to know when the Button is released.

Something like:

val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()

if (isPressed){
    println("Pressed")
    //Use if + DisposableEffect to wait for the press action is completed
    DisposableEffect(Unit) {
        onDispose {
            println("released")
        }
    }
}

Button(onClick={},
    interactionSource = interactionSource
){
    Text("record")
}

enter image description here

0
On

If you're asking just about the press/release actions, I don't know how to do this with a button, but you can achieve the same result using a Box (for instance) and use some modifiers to design it the way you want...

Here is a possible solution.

@Composable
fun TestButton() {
    var isPressed by remember {
        mutableStateOf(false)
    }
    Column {
        Box(
            Modifier
                .pointerInput(Unit) {
                    detectTapGestures(
                        onPress = {
                            try {
                                isPressed = true
                                // Start recording here
                                awaitRelease()
                            } finally {
                                isPressed = false
                                // Stop recording here
                            }
                        },
                    )
                }
                .background(
                    MaterialTheme.colors.primary.copy(alpha = if (isPressed) .88f else 1f),
                    MaterialTheme.shapes.small
                )
                .padding(vertical = 8.dp, horizontal = 16.dp)
        ) {
            Text(
                text = "Press me!",
                Modifier.align(Alignment.Center),
                color = MaterialTheme.colors.onPrimary
            )
        }
        Text(text = if (isPressed) "Pressed" else "Unpressed")
    }
}

Notice that I'm using a Box with a similar design of a Button.

Here is the result:

enter image description here