Skip to content

Instantly share code, notes, and snippets.

@bmc08gt
Last active February 1, 2021 10:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmc08gt/0869fd75f493114f88fefd8b7a69237e to your computer and use it in GitHub Desktop.
Save bmc08gt/0869fd75f493114f88fefd8b7a69237e to your computer and use it in GitHub Desktop.
Auto-dismissing Snackbar for Jetpack Compose
class SnackbarState {
var show by mutableStateOf(false)
}
@Composable
fun TransientSnackbar(
modifier: Modifier = Modifier,
snackbarState: SnackbarState,
text: String,
actionLabel: String,
onAction: () -> Unit,
shape: Shape = MaterialTheme.shapes.small,
autoDismiss: Boolean = true,
timeout: Long = 4_000,
onDismiss: (SnackbarState) -> Unit
) {
if(snackbarState.show) {
Snackbar(
modifier = modifier,
text = { Text(text = text) },
shape = shape,
action = {
ClickableText(
text = AnnotatedString(text = actionLabel),
modifier = Modifier.padding(16.dp),
style = TextStyle(
fontWeight = FontWeight.Bold,
color = MaterialTheme.colors.secondary
),
onClick = {
onAction()
snackbarState.show = false
}
)
}
)
}
if (autoDismiss && snackbarState.show) {
launchInComposition {
delay(timeout)
snackbarState.show = false
onDismiss(snackbarState)
}
}
}
@gtf35
Copy link

gtf35 commented Feb 1, 2021

Looks cool, but how to add dynamically?🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment