尝试使用 Jetpack Compose 显示 AlertDialog,但应用程序在调用 AlertDialog 函数时崩溃,错误为
java.lang.IllegalStateException:组合需要一个活动的组合上下文
请在下面找到代码,
@Composable
fun homeScreenCompose() {
Align(
alignment = Alignment.Center
) {
Column(
arrangement = Arrangement.Center,
modifier = Spacing(16.dp),
children = {
Button(
modifier = Height(50.dp) wraps Expanded,
text = "Alert Dialog", onClick = {
showAlertDialog()
}, style = OutlinedButtonStyle(
Border(color = Color.Red, width = 1.dp),
shape = RoundedCornerShape(50), //50% percent
contentColor = Color.Red,
color = Color.White,
elevation = Dp(4f)
)
)
}
)
}
}
@Composable
fun showAlertDialog() {
val openDialog = +state { true }
if (openDialog.value) {
AlertDialog(
onCloseRequest = {
},
title = {
Text(text = "Logout")
},
text = {
Text("Are you sure you have to logout?")
},
confirmButton = {
Button("Yes", onClick = {
openDialog.value = false
})
},
dismissButton = {
Button("No", onClick = {
openDialog.value = false
})
},
buttonLayout = AlertDialogButtonLayout.Stacked
)
}
}
无法弄清楚它为什么会崩溃以及解决方案是什么,我们将不胜感激。
谢谢你。