我一直在尝试在 Android Jetpack Compose 的动态列表中显示来自 AlertDialog
of onClick
的 Card
。
我收到编译时错误@Composable 调用只能在@Composable 函数的上下文中发生。
下面是我的代码片段:
@Preview(showBackground = true)
@Composable
fun prepareCard(card: Card) {
MyApplicationTheme() {
androidx.compose.material.Card() {
Column(Modifier.clickable {
Log.d("TAG", "clicked : " + card.name)
val showDialog = mutableStateOf(true)
if (showDialog.value) {
alert(card)
}
...
}
}
}
我制作了 alert()
可组合函数,可以从上面的代码中调用
@Composable
fun alert(card : Card) {
AlertDialog(
title = {
Text("")
},
text = {
Text(text = card.name)
}, onDismissRequest = {
},
confirmButton = {},
dismissButton = {}
)
}
如图所示,我收到编译时错误
请帮忙解决这个问题
注意:
我尝试过如下修改,它解决了编译时错误,但点击 AlertDialog
时仍然没有显示 Card
@Preview(showBackground = true)
@Composable
fun prepareCard(card: Card) {
MyApplicationTheme() {
val showDialog = mutableStateOf(false)
if (showDialog.value) {
alert(card)
}
androidx.compose.material.Card() {
Column(Modifier.clickable {
Log.d("kushal", "clicked : " + card.name)
showDialog.value = true
}) {
...
}
}
答案 0 :(得分:3)
您可以像下面的代码一样更新您的代码 ->
@Composable
fun alert() {
MaterialTheme {
Column {
val openDialog = remember { mutableStateOf(false) }
Button(onClick = {
openDialog.value = true
}) {
Text("Click me")
}
if (openDialog.value) {
AlertDialog(
onDismissRequest = {
// Dismiss the dialog when the user clicks outside the dialog or on the back
// button. If you want to disable that functionality, simply use an empty
// onCloseRequest.
openDialog.value = false
},
title = {
Text(text = "Dialog Title")
},
text = {
Text("Here is a text ")
},
confirmButton = {
Button(
onClick = {
openDialog.value = false
}) {
Text("This is the Confirm Button")
}
},
dismissButton = {
Button(
onClick = {
openDialog.value = false
}) {
Text("This is the dismiss Button")
}
}
)
}
}
}
}
答案 1 :(得分:2)
使用 remember
中的 showDialog
解决不显示 AlertDialog
的问题。
val showDialog = remember { mutableStateOf(false) }
if (showDialog.value) {
//alert...
}
Card(){
Column(Modifier.clickable(
onClick = {showDialog.value = true})
){}
}
同样在您的 alert()
函数中,您应该处理状态。
@Composable
fun alert(name : String,
showDialog: Boolean,
onDismiss: () -> Unit) {
if (showDialog) {
AlertDialog(
title = {
Text("Title")
},
text = {
Text(text = name)
},
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = onDismiss ) {
Text("OK")
}
},
dismissButton = {}
)
}
}
并调用它:
val showDialog = remember { mutableStateOf(false) }
Card(){
if (showDialog.value) {
alert(name = "Name",
showDialog = showDialog.value,
onDismiss = {showDialog.value = false})
}
Column(Modifier.clickable(
onClick = {showDialog.value = true})
){}
}
答案 2 :(得分:0)
这是使用状态显示对话框的推荐方式。
val openDialog = remember { mutableStateOf(true) }
val dialogWidth = 200.dp
val dialogHeight = 50.dp
if (openDialog.value) {
Dialog(onDismissRequest = { openDialog.value = false }) {
// Draw a rectangle shape with rounded corners inside the dialog
Box(Modifier.size(dialogWidth, dialogHeight).background(Color.White))
}
}