For a android.widget.Button I can use performClick() to simulate a click programmatically. But I don't know how to do it in Jetpack Compose. I've looked into the compose.material documentation but I at least coudn't find anything about this.
With this solution you will get the ripple effect programmatically like you have pressed the button:
1) Create interactionSource:
val interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
2) Create coroutine scope:
val coroutine = rememberCoroutineScope()
3) In your button set interaction source:
Button(
onClick = {
vm.myFunction()
},
//important
interactionSource = interactionSource,
.
.
.
)
4) Finally call it like so from anywhere:
coroutine.launch {
val press = PressInteraction.Press(Offset.Zero)
interactionSource.emit(press)
vm.myFunction()
delay(300)
interactionSource.emit(PressInteraction.Release(press))
}
In compose you're creating a button with action. You can pass action function and call same function programmatically.
// 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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With