Last active
February 1, 2021 10:12
-
-
Save bmc08gt/0869fd75f493114f88fefd8b7a69237e to your computer and use it in GitHub Desktop.
Auto-dismissing Snackbar for Jetpack Compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks cool, but how to add dynamically?🤔