Home > Back-end >  Jetpack compose snackbar action click is not working
Jetpack compose snackbar action click is not working

Time:09-23

  • I have displayed a snackbar with specific action in Jetpack compose but click listener on that action is not working.

Here is my code:

@Composable
fun MySnackBar() {
        Snackbar(
            modifier = Modifier.padding(4.dp),
            action = {
                TextButton(color = LightBlue,onClick = {
                  Log.d("TAG", "Action clicked!")
                }) {
                    Text(text = "Remove")
                }
            }
        ) {
            Text(text = "This is a basic Snackbar with action item")
        }
    }

CodePudding user response:

In a Scaffold you can use:

   val scope = rememberCoroutineScope()
   scope.launch {

        val snackbarResult = scaffoldState.snackbarHostState.showSnackbar(
            message = "This is a basic Snackbar with action item",
            actionLabel = "Remove"
        )
        when (snackbarResult) {
            SnackbarResult.Dismissed -> {}
            SnackbarResult.ActionPerformed -> {}
        }
    }

enter image description here

If you don't have a Scaffold you can use something like:

        val snackState = remember { SnackbarHostState() }
        SnackbarHost(hostState = snackState, Modifier){ data ->
            Snackbar(
                actionColor = Red,
                snackbarData = data
            )
        }

and then use the same code above to show the Snackbar changing scaffoldState.snackbarHostState to snackState.

CodePudding user response:

Button( onClick = { Snackbar(action = {}) { Text("hello") } }`

  • Related