Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpackandroid-snackbar

Jetpack Compose, how to change the color of the action of the snackbar in .showSnackbar() in a Scaffold?


So, I'm showing a snackbar inside of my Scaffold, using the scaffoldState.snackbarHostState.showSnackbar() method, though the colour of the "Undo" action is dark purple, and I would like to change it to something else.

I know that I can show it as a custom component, though I would like to launch it in a coroutineScope(), which I think is not possible.

My code is like this for the snackbar.

scope.launch {
  val result = scaffoldState.snackbarHostState.showSnackbar(
    message = "Note Deleted",
    actionLabel = "Undo",
  )
  if (result == SnackbarResult.ActionPerformed) { 
    viewModel.onEvent(NotesEvent.RestoreNote)
  }
}

I would like to know if it's possible to change the text colour of the action here and if yes, it would be cool if you could give an example or a resource.

Thanks!


Solution

  • You can customize your Snackbar using the actionColor parameter.

    Something like:

    val scaffoldState = rememberScaffoldState()
    Scaffold(
        scaffoldState = scaffoldState,
        snackbarHost = {
            // reuse default SnackbarHost to have default animation and timing handling
            SnackbarHost(it) { data ->
                // custom snackbar with the custom colors
                Snackbar(
                    actionColor = Green,
                    //contentColor = ...,
                    snackbarData = data
                )
            }
        },
    

    Then just use it:

    scope.launch {
            scaffoldState.snackbarHostState.showSnackbar(
                   message = "Note Deleted",
                   actionLabel = "Undo"
             )
    }
    

    enter image description here