Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically click a Button in Jetpack Compose?

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.

like image 641
daniyelp Avatar asked Mar 09 '26 22:03

daniyelp


2 Answers

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))
}
like image 80
F.Mysir Avatar answered Mar 12 '26 12:03

F.Mysir


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")
}
like image 40
Philip Dukhov Avatar answered Mar 12 '26 12:03

Philip Dukhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!