我尝试在按下按钮时显示AlertDialog。对于AlertDialog,我有一个可组合的函数- showDialog。很明显,这个函数调用了一个对话框。我有另一个可组合的功能,显示一些窗口与文本和按钮。当按钮被点击时,我想调用一个存储AlertDialog的函数。
AlertDialog身体:
fun monthDialog() {
val openDialog = remember { mutableStateOf(true) }
if (openDialog.value) {
AlertDialog(
onDismissRequest = {
openDialog.value = false
},
title = {
Text(text = "Title")
},
text = {
Text(
"This area typically contains the supportive text " +
"which presents the details regarding the Dialog's purpose."
)
},
buttons = {
Row(
modifier = Modifier.padding(all = 8.dp),
horizontalArrangement = Arrangement.Center
) {
Button(
modifier = Modifier.fillMaxWidth(),
onClick = { openDialog.value = false }
) {
Text("Dismiss")
}
}
}
)
}
首先,我尝试了我想到的最简单的解决方案:
IconButton(onClick = monthDialog())
和得到错误(@Composable调用只能从@Composable函数的上下文中发生)
在我使用mutablestateof和以下条件尝试正常触发后:
val showDialog = remember { mutableStateOf(false)}
if(showDialog.value == true) monthDialog()
在onClick事件中添加如下内容:
monthHeader(onClick = {showDialog.value = !showDialog.value})
,这是工作....但是又丑又坏。这是第一次很好地工作。但是在第一次点击之后,我需要再点击两次来再次触发该事件。
按钮代码片段:
fun Calendar (){
//...
val showDialog = remember { mutableStateOf(false)}
if(showDialog.value == true) monthDialog()
Card(
){
Column(){
IconButton(onClick ={
monthDialog() // error here
//showDialog.value = !showDialog.value
}
}
}
在Google上搜索了几个小时之后我尝试我自己的解决方案
val clicked = remember { mutableStateOf(false)}
val showDialog = remember { mutableStateOf(false)}
if(showDialog.value) monthDialog()
else if(clicked.value) monthDialog()
Card(){
Column(){
monthHeader(onClick = {
clicked.value = showDialog.value
showDialog.value = !clicked.value
})
}
}
但在我看来,这是拐杖/拼凑
在这里留下一个更好的解决方案(imho):
提升对话的状态
@Composable
fun MonthDialog(onClose: () -> Unit) {
AlertDialog(
onDismissRequest = onClose,
title = {
Text(text = "Title")
},
text = {
Text(
"This area typically contains the supportive text " +
"which presents the details regarding the Dialog's purpose."
)
},
buttons = {
Row(
modifier = Modifier.padding(all = 8.dp),
horizontalArrangement = Arrangement.Center
) {
Button(
modifier = Modifier.fillMaxWidth(),
onClick = onClose
) {
Text("Dismiss")
}
}
}
)
注意,我从这个组件中删除了状态,使其无状态。这个组件只会在对话框关闭时发出通知。
现在你可以像这样调用对话框:
var showDialog by remember { mutableStateOf(false) }
if (showDialog) {
MonthDialog(onClose = { showDialog = false })
}
Card {
MonthHeader( // use upper case for naming your composables
onClick = {
showDialog = true
}
)
}
也可以使用Modifier
/PointerInputScope
:
modifier = Modifier.pointerInput(Unit) {
detectTapGestures(
onPress = { },
onTap = { },
onDoubleTap = { },
onLongPress = { }
)