Dialogs是在应用程序中显示一些额外信息或进行用户交互的常见功能。Jetpack Compose中的Dialog可以通过使用AlertDialog
组件来创建。
基本用法
下面通过示例来了解Dialog的使用。
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlertDialogExample(onDismissRequest: () -> Unit,onConfirmation: () -> Unit,dialogTitle: String,dialogText: String,icon: ImageVector,
) {AlertDialog(icon = {Icon(icon, contentDescription = "Example Icon")},title = {Text(text = dialogTitle)},text = {Text(text = dialogText)},onDismissRequest = {onDismissRequest()},confirmButton = {TextButton(onClick = {onConfirmation()}) {Text("Confirm")}},dismissButton = {TextButton(onClick = {onDismissRequest()}) {Text("Dismiss")}})
}
运行效果如下图所示。
在AlertDialog中,
- icon用于显示图标
- title用于显示标题
- text用于显示内容
- confirmButton用于显示确认按钮
- dismissButton用于显示取消按钮
自定义对话框布局
AlertDialog使用内置的布局,
@Composable
fun DialogWithImage(onDismissRequest: () -> Unit,onConfirmation: () -> Unit,painter: Painter,imageDescription: String,
) {var showDialog by remember {mutableStateOf(true)}if(showDialog){Dialog(onDismissRequest = { onDismissRequest() }) {// Draw a rectangle shape with rounded corners inside the dialogCard(modifier = Modifier.fillMaxWidth().height(375.dp).padding(16.dp),shape = RoundedCornerShape(16.dp),) {Column(modifier = Modifier.fillMaxSize(),verticalArrangement = Arrangement.Center,horizontalAlignment = Alignment.CenterHorizontally,) {Image(painter = painter,contentDescription = imageDescription,contentScale = ContentScale.Fit,modifier = Modifier.height(160.dp))Text(text = "带按钮和图片的弹框",modifier = Modifier.padding(16.dp),)Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.Center,) {TextButton(onClick = { onDismissRequest()showDialog = !showDialog},modifier = Modifier.padding(8.dp),) {Text("取消")}TextButton(onClick = { onConfirmation()showDialog = !showDialog},modifier = Modifier.padding(8.dp),) {Text("确认")}}}}}}
}
运行效果如下图所示
在本例中,Dialog的子控件是一个Card控件,Card控件的子控件为Column,Column的子控件有Image、Text、和Row,Row的子空间是2给TextButton。除了上面的样式,在Card容器中可以根据想要达到的效果添加不同的控件,从而得到自定义布局的Dialog。
示例代码已上传到github,地址如下
示例工程代码