Compose中实现点击关闭按钮隐藏Modal BottomSheet的方案
解决方案
要实现三种关闭方式且不直接暴露ModalBottomSheetState,可以通过内部封装关闭逻辑+传递关闭回调的方式实现,具体步骤如下:
1. 重构组件参数,传递关闭回调
修改CDSModelBottomSheet的toolBar参数,让它接收一个带onClose回调的Composable函数,这样工具栏内的关闭按钮可以调用该回调触发关闭。同时内部通过rememberCoroutineScope处理协程操作(因为sheetState.hide()是挂起函数)。
@Composable fun CDSModelBottomSheet( toolBar: @Composable (onClose: () -> Unit) -> Unit, content: @Composable () -> Unit ) { val modelBottomSheetState = rememberModalBottomSheetState( initialValue = ModalBottomSheetValue.Expanded, // 允许状态从展开切换到隐藏 confirmStateChange = { it != ModalBottomSheetValue.Hidden || true } ) val coroutineScope = rememberCoroutineScope() // 封装内部关闭逻辑 val closeBottomSheet = { coroutineScope.launch { modelBottomSheetState.hide() } } ModalBottomSheetLayout( sheetState = modelBottomSheetState, sheetShape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp), // 开启背景点击关闭功能 scrimClickable = true, sheetContent = { Column { // 将关闭回调传递给工具栏 toolBar(onClose = closeBottomSheet) content() } } ) {} }
2. 在预览中绑定关闭回调
在PreviewCDSBottomSheet里,接收onClose参数并绑定到关闭按钮的点击事件:
@Composable @Preview fun PreviewCDSBottomSheet() { CDSModelBottomSheet( toolBar = { onClose -> Toolbar( title = "Select Account", trailingIcon = { IconButton( modifier = Modifier.size(24.dp), onClick = onClose // 调用关闭回调 ) { Icon( imageVector = Icons.Filled.Close, contentDescription = stringResource(R.string.close_bottom_sheet), tint = Color.Black, ) } } ) }, content = { LoginMode() } ) }
三种关闭方式说明
- 拖拽关闭:
rememberModalBottomSheetState默认支持拖拽交互,无需额外配置。 - 点击背景关闭:通过设置
scrimClickable = true,ModalBottomSheetLayout会自动处理背景点击事件,触发Sheet隐藏。 - 点击关闭按钮:通过传递
onClose回调,让按钮直接调用内部封装的关闭逻辑,无需暴露sheetState。
内容的提问来源于stack exchange,提问作者ant2009
相关产品推荐
相关产品推荐

