jetpack compose 中的 onPressIn 和 onPressOut

Oma*_*led 6 android kotlin android-jetpack-compose android-compose-button android-jetpack-compose-button

我有录制语音的按钮,所以我希望它在用户按下它时开始录制,并在用户离开时停止录制

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

}
Run Code Online (Sandbox Code Playgroud)

ngl*_*ber 8

如果您只是询问按下/释放操作,我不知道如何使用按钮来执行此操作,但是您可以使用(例如Box)获得相同的结果,并使用一些修饰符按照您想要的方式设计它...

这是一个可能的解决方案。

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

Run Code Online (Sandbox Code Playgroud)

请注意,我使用的 aBox与 a 的设计类似Button

结果如下:

在此输入图像描述


Gab*_*tti 7

要获取 a 中的按下/释放操作,Button您可以使用 来InteractionSource.collectIsPressedAsState了解是否Button按下了。
您可以添加副作用来了解何时Button释放。

就像是:

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")
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述