如何以编程方式单击 Jetpack Compose 中的按钮?

dan*_*elp 7 android android-jetpack android-jetpack-compose

对于android.widget.Button我可以用来performClick()以编程方式模拟点击。但我不知道如何在 Jetpack Compose 中做到这一点。我查看了compose.material文档,但至少我找不到任何关于此的信息。

F.M*_*sir 8

使用此解决方案,您将以编程方式获得连锁反应,就像按下按钮一样:

1)创建交互源:

val interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
Run Code Online (Sandbox Code Playgroud)

2)创建协程作用域:

val coroutine = rememberCoroutineScope()
Run Code Online (Sandbox Code Playgroud)

3)在您的按钮设置交互源中:

Button(
    onClick = {
        vm.myFunction()
    },
    //important
    interactionSource = interactionSource,
    .
    .
    .
)
Run Code Online (Sandbox Code Playgroud)

4)最后从任何地方这样调用它:

coroutine.launch {
    val press = PressInteraction.Press(Offset.Zero)
    interactionSource.emit(press)
    vm.myFunction()
    delay(300)
    interactionSource.emit(PressInteraction.Release(press))
}
Run Code Online (Sandbox Code Playgroud)

  • 我不会说这更好。也许刚刚好。完美的场景是当按钮显示为被单击时调用“onClick”方法。在任何情况下,当按钮显示为已单击时,我都不希望调用“onClick”。 (2认同)

Phi*_*hov 5

在撰写中,您正在创建一个带有操作的按钮。您可以传递操作函数并以编程方式调用相同的函数。

// you need to remember your callback to prevent extra recompositions.
// pass all variables that may change between recompositions
// as keys instead of `Unit`
val onClickAction = remember(Unit) { 
    {
        
        // do some action
    }
}

LaunchedEffect(Unit) {
    // perform action in 1 sec after view appear
    delay(1000)
    onClickAction()
}
Button(
    onClick = onClickAction
) {
    Text(text = "Button")
}
Run Code Online (Sandbox Code Playgroud)