Created
August 2, 2025 16:30
-
-
Save zerofancy/98becf7f4b7987ca628939f04e6132ff to your computer and use it in GitHub Desktop.
Compose中弹出对话框
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import androidx.compose.foundation.layout.Arrangement | |
| import androidx.compose.foundation.layout.Column | |
| import androidx.compose.foundation.layout.fillMaxSize | |
| import androidx.compose.foundation.layout.padding | |
| import androidx.compose.material3.Button | |
| import androidx.compose.material3.MaterialTheme | |
| import androidx.compose.material3.Text | |
| import androidx.compose.runtime.getValue | |
| import androidx.compose.runtime.mutableStateOf | |
| import androidx.compose.runtime.remember | |
| import androidx.compose.runtime.setValue | |
| import androidx.compose.ui.Alignment | |
| import androidx.compose.ui.Modifier | |
| import androidx.compose.ui.unit.dp | |
| import androidx.compose.ui.window.DialogProperties | |
| import androidx.compose.material3.AlertDialog | |
| import androidx.compose.runtime.Composable | |
| // 主界面 | |
| @Composable | |
| fun NovelDialogScreen() { | |
| // 状态管理:控制对话框是否显示 | |
| var showDialog by remember { mutableStateOf(false) } | |
| Column( | |
| modifier = Modifier | |
| .fillMaxSize() | |
| .padding(24.dp), | |
| horizontalAlignment = Alignment.CenterHorizontally, | |
| verticalArrangement = Arrangement.Center | |
| ) { | |
| // 触发对话框的按钮 | |
| Button(onClick = { showDialog = true }) { | |
| Text("显示对话框") | |
| } | |
| // 对话框组件(Compose微件) | |
| if (showDialog) { | |
| AlertDialog( | |
| // 对话框标题 | |
| title = { | |
| Text( | |
| text = "主神空间", | |
| style = MaterialTheme.typography.headlineSmall | |
| ) | |
| }, | |
| // 对话框内容 | |
| text = { | |
| Text( | |
| text = "你想知道生命的意义吗,你想真正地活着吗?", | |
| style = MaterialTheme.typography.bodyLarge | |
| ) | |
| }, | |
| // 确认按钮(是) | |
| confirmButton = { | |
| Button( | |
| onClick = { | |
| showDialog = false | |
| // 这里可以添加"是"的逻辑,如打开《无限恐怖》 | |
| openUrl("https://www.qidian.com/book/1003118186/") | |
| } | |
| ) { | |
| Text("是") | |
| } | |
| }, | |
| // 取消按钮(否) | |
| dismissButton = { | |
| Button( | |
| onClick = { | |
| showDialog = false | |
| // 这里可以添加"否"的逻辑,如打开《无限曙光》 | |
| openUrl("https://www.qidian.com/book/1004618281/") | |
| } | |
| ) { | |
| Text("否") | |
| } | |
| }, | |
| // 对话框属性配置 | |
| properties = DialogProperties( | |
| // 点击外部是否关闭对话框 | |
| dismissOnClickOutside = false, | |
| // 按返回键是否关闭对话框 | |
| dismissOnBackPress = true | |
| ), | |
| // 对话框关闭回调 | |
| onDismissRequest = { | |
| showDialog = false | |
| } | |
| ) | |
| } | |
| } | |
| } | |
| // 跨平台打开URL的声明(需要平台实现) | |
| expect fun openUrl(url: String) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment