gpt4 book ai didi

android-jetpack-compose - Snackbar 永远不会被关闭(Jetpack Compose SnackbarHostState)

转载 作者:行者123 更新时间:2023-12-04 17:22:05 41 4
gpt4 key购买 nike

描述

SnackbarHostState 上调用 showSnackbar 并传递 duration 参数不会关闭 Snackbar。协程似乎无限期暂停。

重现步骤:

val snackbarHostState = remember{mutableStateOf(SnackbarHostState())}

Column {
Button(
onClick = {
lifecycleScope.launch {
val time = System.currentTimeMillis()
Log.d(TAG, "showing snackbar")
snackbarHostState.value.showSnackbar(
message = "Hey look a snackbar",
actionLabel = "Hide",
duration = SnackbarDuration.Short
)
Log.d(TAG, "done ${System.currentTimeMillis()-time}") // <-- Never called
}
}
) {
Text("Show snackbar")
}
snackbarHostState.value.currentSnackbarData?.let { snackbarData ->
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val snackbar = createRef()
Snackbar(
modifier = Modifier.constrainAs(snackbar) {
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
},
snackbarData = snackbarData,
)
}
}
}

最佳答案

我想您需要将 Snackbar 包装在 SnackbarHost 中,因为这会按预期工作。

val snackbarHostState = remember{mutableStateOf(SnackbarHostState())}

Column {
Button(
onClick = {
lifecycleScope.launch {
val time = System.currentTimeMillis()
Log.d(TAG, "showing snackbar")
snackbarHostState.value.showSnackbar(
message = "Hey look a snackbar",
actionLabel = "Hide",
duration = SnackbarDuration.Short
)
Log.d(TAG, "done ${System.currentTimeMillis()-time}") // <-- Never called
}
}
) {
Text("Show snackbar")
}
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val snackbar = createRef()
SnackbarHost(
modifier = Modifier.constrainAs(snackbar) {
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
},
hostState = snackbarHostState.value,
snackbar = {
Snackbar(
action = {
TextButton(onClick = {
snackbarHostState.value.currentSnackbarData?.dismiss()
}) {
Text(
text = "Hide",
)
}
}
) {
Text("hey look a snackbar")
}
}
)
}
}

关于android-jetpack-compose - Snackbar 永远不会被关闭(Jetpack Compose SnackbarHostState),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65587203/

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