onPressIn and onPressOut in jetpack compose
M

2

6

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")
   }

}
Morelos answered 13/9, 2021 at 2:25 Comment(2)
You didn't try any voice recording codes? Try search in Google.Coax
I tried but I didn't find on github or googleMorelos
N
8

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

Nebo answered 13/9, 2021 at 3:17 Comment(0)
A
7

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

Arnaldo answered 13/9, 2021 at 5:53 Comment(2)
Thanks. That was awsome.Froward
Thank you. Thanks a lot. I am glad I found your answer. It short, sweet and simple.Kissie

© 2022 - 2024 — McMap. All rights reserved.