Jetpack Compose中如何区分AlertDialog的两种关闭触发动作?
解决方案
原生AlertDialog的onDismissRequest回调本身不携带触发来源信息,无法直接从回调参数区分是点击外部区域还是按下返回键触发。但你要实现的「仅返回键关闭对话框、点击外部不关闭」的需求不需要做触发场景区分,直接通过AlertDialog的自带配置就能实现:
方案1:使用AlertDialog自带属性配置(推荐)
Material 2 版本AlertDialog配置
设置AlertDialog的properties参数,将dismissOnClickOutside设为false即可,此时点击外部区域不会触发onDismissRequest,只有按下返回键会触发该回调:
AlertDialog( onDismissRequest = { // 仅按下返回键会触发该回调,直接执行关闭逻辑 openDialog = false }, title = { Text("提示") }, text = { Text("对话框内容") }, confirmButton = { Button(onClick = { openDialog = false }) { Text("确认") } }, // 核心配置 properties = DialogProperties( dismissOnClickOutside = false, // dismissOnBackPress 默认值为true,即允许返回键关闭,可省略不写 ) )
Material 3 版本AlertDialog配置
直接将AlertDialog的dismissOnClickOutside参数设为false即可:
AlertDialog( onDismissRequest = { openDialog = false }, title = { Text("提示") }, text = { Text("对话框内容") }, confirmButton = { Button(onClick = { openDialog = false }) { Text("确认") } }, // 核心配置 dismissOnClickOutside = false, // dismissOnBackPress 默认值为true,即允许返回键关闭,可省略不写 )
方案2:手动区分两种触发场景(仅需分别处理两类触发逻辑时使用)
如果你确实需要针对点击外部、按下返回键做不同的业务处理,可以手动接管返回键监听,实现场景区分:
var openDialog by remember { mutableStateOf(true) } if (openDialog) { // 接管返回键事件 BackHandler { // 此处为按下返回键的专属逻辑 openDialog = false // 可在此处添加返回键触发时的其他业务代码 } AlertDialog( onDismissRequest = { // 此处为点击外部区域的专属逻辑 // 不需要关闭就留空,或者添加点击外部触发时的其他业务代码 }, title = { Text("提示") }, text = { Text("对话框内容") }, confirmButton = { Button(onClick = { openDialog = false }) { Text("确认") } }, properties = DialogProperties( dismissOnBackPress = false, // 禁用默认返回键关闭逻辑,交给BackHandler处理 dismissOnClickOutside = true // 保持点击外部触发onDismissRequest ) ) }
内容的提问来源于stack exchange,提问作者progquester
相关产品推荐
相关产品推荐

