我创建了一个小例子。我希望它对你有帮助。在我的情况下,我通过单击按钮生成一个“事件”
class ComposeActivity5 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTutorialTheme {
Composable1()
}
}
}
}
@Composable
fun Composable1() {
val scaffoldState = rememberScaffoldState()
var showHide by remember { mutableStateOf(false) }
var pressCount by remember { mutableStateOf(0) }
Scaffold(
scaffoldState = scaffoldState,
content = { innerPadding ->
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
) {
Button(onClick = {
pressCount++
showHide = true
}) {
Text(text = "Test")
}
Composable2(scaffoldState, showHide, pressCount) {
showHide = false
}
}
}
)
}
@Composable
fun Composable2(
scaffoldState: ScaffoldState,
showHide: Boolean,
pressCount: Int,
onDismiss: () -> Unit
) {
val mostRecentOnDismiss by rememberUpdatedState(onDismiss)
LaunchedEffect(scaffoldState, showHide) {
if (showHide) {
scaffoldState.snackbarHostState.showSnackbar(
message = "We are ignore press button to show Snackbar. Total number of clicks $pressCount",
actionLabel = "Close",
duration = SnackbarDuration.Short,
)
mostRecentOnDismiss()
}
}
}