android 如何在Jetpack Compose中显示带有onclick按钮的snackbar

eyh26e7m  于 2022-12-02  发布在  Android
关注(0)|答案(8)|浏览(321)

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

Button(onClick = {
    Snackbar(action = {}) {
        Text("hello")
    }
}

但是AS说“@Composable调用只能从@Composable函数的上下文中发生”
你能给予我一个好节目吗?
我希望它能在Button.onclick()中运行

aor9mmx1

aor9mmx11#

您需要两样东西:

  1. SnackbarHostState-它将管理Snackbar的状态(* 您通常会从ScaffoldState获得该信息 *)
  2. 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")
        }
    }
}

kgsdhlau

kgsdhlau2#

在Bartek的答案的基础上,你还可以使用Compose的副作用,这样你就不必管理CoroutineScope本身。
由于Composables本身应该没有副作用,因此建议使用Compose's Effect APIs,以便以可预测的方式执行这些副作用。
在您的特定情况下,您可以使用LaunchedEffect API在可组合的范围内运行suspend函数。示例代码如下所示:

@Composable
fun SnackbarDemo() {
    val scaffoldState = rememberScaffoldState() // this contains the `SnackbarHostState`
    val (showSnackBar, setShowSnackBar) = remember {
        mutableStateOf(false)
    }
    if (showSnackBar) {
        LaunchedEffect(scaffoldState.snackbarHostState) {
            // Show snackbar using a coroutine, when the coroutine is cancelled the
            // snackbar will automatically dismiss. This coroutine will cancel whenever
            // `showSnackBar` is false, and only start when `showSnackBar` is true
            // (due to the above if-check), or if `scaffoldState.snackbarHostState` changes.
            val result = scaffoldState.snackbarHostState.showSnackbar(
                message = "Error message",
                actionLabel = "Retry message"
            )
            when (result) {
                SnackbarResult.Dismissed -> {
                    setShowSnackBar(false)
                }
                SnackbarResult.ActionPerformed -> {
                    setShowSnackBar(false)
                    // perform action here
                }
            }
        }
    }
    Scaffold(
        modifier = Modifier,
        scaffoldState = scaffoldState // attaching `scaffoldState` to the `Scaffold`
    ) {
        Button(
            onClick = {
                setShowSnackBar(true)
            }
        ) {
            Text(text = "A button that shows a Snackbar")
        }
    }
}
41ik7eoe

41ik7eoe3#

你可以用这个

@Composable
fun MainScreen() {
    val coroutineScope = rememberCoroutineScope()
    val showSnackBar: (
        message: String?,
        actionLabel: String,
        actionPerformed: () -> Unit,
        dismissed: () -> Unit
    ) -> Unit = { message, actionLabel, actionPerformed, dismissed ->
        coroutineScope.launch {
            val snackBarResult = scaffoldState.snackbarHostState.showSnackbar(
                message = message.toString(),
                actionLabel = actionLabel
            )
            when (snackBarResult) {
                SnackbarResult.ActionPerformed -> actionPerformed.invoke()
                SnackbarResult.Dismissed -> dismissed.invoke()
            }
        }
    }

    showSnackBar.invoke(
        "YOUR_MESSAGE",
        "ACTION_LABEL",
        {
         //TODO ON ACTION PERFORMED
        },
        {
         //TODO ON DISMISSED
        }
    )
}
amrnrhlw

amrnrhlw4#

如果您使用新的材料3,则支架中会有新字段:“小吃店主机”

val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()

Scaffold(
  snackbarHost = { SnackbarHost(snackbarHostState) },
  ...

            // for showing snackbar in onClick for example:
            scope.launch {
                snackbarHostState.showSnackbar(
                    "Snackbar Test"
                )
            }
vql8enpb

vql8enpb5#

首先,您需要一个SnackbarHostState,您可以将此状态向下传递给您的组合对象,在其中您希望触发snackbar消息。或者,如果您使用scaffold,请使用scaffoldState.snackbarHostState

val snackbarHostState = remember { SnackbarHostState() }

显示小吃店是一个副作用,应该 Package 在LaunchEffect可组合

@Composable
fun MyScreen(
    scaffoldState: ScaffoldState = rememberScaffoldState()
) {
   Scaffold(scaffoldState = scaffoldState) {    

     Button(onClick = {
      LaunchedEffect(scaffoldState.snackbarHostState) {
         scaffoldState.snackbarHostState.showSnackbar(
                  message = "hello world",
                  actionLabel = "Retry"
         )
      }

    
     // ...
    }
}

更多信息请访问https://developer.android.com/topic/architecture/ui-layer/events#consuming-trigger-updates
https://developer.android.com/jetpack/compose/side-effects的值

pprl5pva

pprl5pva6#

您也可以使用SnackBar Composable显示没有Scaffold的snackBar。

Box(modifier = Modifier.fillMaxSize()) {
    var showSnackbar by remember {
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = showSnackbar) {
        if (showSnackbar) {
            delay(2000)
            showSnackbar = false
        }
    }

    Column {

        Button(onClick = {
            showSnackbar = !showSnackbar
        }) {
            Text("Show Snackbar")
        }
    }

    if (showSnackbar) {
        androidx.compose.material.Snackbar(modifier = Modifier.align(Alignment.BottomStart),
            action = {
                Text(text = "Action",
                    color = Color(0xffCE93D8),
                    modifier = Modifier.clickable {
                        showSnackbar = false
                    }
                )
            }) {
            androidx.compose.material.Text("Message")
        }
    }
}

LaunchedEffect是将其从合成中删除,如果愿意,可以使用幻灯片动画。

qvsjd97n

qvsjd97n7#

让我补充一个答案,我没有使用脚手架,而是使用状态吊装。

val loginState by viewModel.uiState.collectAsState() // STATE HOISTING
val snackbarHostState = remember { SnackbarHostState() }
val message = stringResource(id = R.string.error_login) 
if (loginState.snackbarVisible) { // When passing true, show snackbar
    LaunchedEffect(snackbarHostState) {
        snackbarHostState.showSnackbar(
            message = message,
            actionLabel = "Do something."
        )
    }
}

Box(
    modifier = Modifier.fillMaxSize()
) {
    // Your screen content
    // ...
    SnackbarHost(
        hostState = snackbarHostState,
        modifier = Modifier.align(Alignment.BottomCenter)
    ) // Snackbar location
}
gfttwv5a

gfttwv5a8#

为了防止您需要一个snackbar作为一个单独的函数,以便在其他屏幕中使用自定义参数进行调用,并且不使用scaffold,我在下面使用了这个函数。
参数openSnackbar: (Boolean) -> Unit用于重置打开条件var openMySnackbar by remember { mutableStateOf(false) },并允许在其他时间打开snackbar。

@Composable
    fun SnackbarWithoutScaffold(
        message: String,
        showSb: Boolean,
        openSnackbar: (Boolean) -> Unit
    ) {
    
        val snackState = remember { SnackbarHostState() }
        val snackScope = rememberCoroutineScope()
    
        SnackbarHost(
            modifier = Modifier,
            hostState = snackState
        ){
            Snackbar(
                snackbarData = it,
                backgroundColor = Color.White,
                contentColor = Color.Blue
            )
        }
    
    
        if (showSb){
            LaunchedEffect(Unit) {
                snackScope.launch { snackState.showSnackbar(message) }
                openSnackbar(false)
            }
   
        }
    
    
    }

并这样使用:
@可组合的乐趣MyScreen(){

var openMySnackbar by remember { mutableStateOf(false)  }
var snackBarMessage by remember { mutableStateOf("") }

Column() {

    Button(
        shape = RoundedCornerShape(50.dp),
        onClick = {
            openMySnackbar = true
            snackBarMessage = "Your message"
        },
    ) {
        Text(text = "Open Snackbar")
    }

    SnackbarWithoutScaffold(snackBarMessage, openMySnackbar, , {openMySnackbar = it})
}

}

相关问题