gpt4 book ai didi

android - 如何在 Jetpack Compose 中通过单击按钮显示 snackbar

转载 作者:行者123 更新时间:2023-12-04 12:21:37 26 4
gpt4 key购买 nike

我想在 Jetpack Compose 中显示带有按钮 onclick 的 snackbar
我试过这个

Button(onClick = {
Snackbar(action = {}) {
Text("hello")
}
}
但是 AS 说“@Composable 调用只能在 @Composable 函数的上下文中发生”
你能给我一个很好的程序吗?
我希望它可以在 Button.onclick() 中运行

最佳答案

你需要两件事:

  • SnackbarHostState - 它将管理您的 Snackbar 的状态
    (您通常会从 ScaffoldState 获得)
  • CoroutineScope - 负责showing您的 Snackbar

  • @Composable
    fun SnackbarDemo() {
    val scaffoldState = rememberScaffoldState() // this contains the `SnackbarHostState`
    val coroutineScope = rememberCoroutineScope()

    Scaffold(
    modifier = Modifier,
    scaffoldState = scaffoldState // attaching `scaffoldState` to the `Scaffold`
    ) {
    Button(
    onClick = {
    coroutineScope.launch { // using the `coroutineScope` to `launch` showing the snackbar
    // taking the `snackbarHostState` from the attached `scaffoldState`
    val snackbarResult = scaffoldState.snackbarHostState.showSnackbar(
    message = "This is your message",
    actionLabel = "Do something."
    )
    when (snackbarResult) {
    Dismissed -> Log.d("SnackbarDemo", "Dismissed")
    ActionPerformed -> Log.d("SnackbarDemo", "Snackbar's button clicked")
    }
    }
    }
    ) {
    Text(text = "A button that shows a Snackbar")
    }
    }
    }
    example

    关于android - 如何在 Jetpack Compose 中通过单击按钮显示 snackbar ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68909340/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com