You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose:如何禁止用户操作ModalBottomSheet,仅保留程序化控制

解决ModalBottomSheet仅支持程序化交互的问题

你遇到的点击背景关闭Sheet的问题,是因为在Material3 1.4.0-alpha08及之后的版本中,ModalBottomSheetProperties新增了控制外部点击关闭的配置项,你当前的代码遗漏了这个设置。同时代码里还存在变量名不一致的小错误,以下是修正后的完整实现:

val bottomSheetState = rememberModalBottomSheetState(
    confirmValueChange = { sheetValue -> sheetValue != SheetValue.PartiallyExpanded },
    skipPartiallyExpanded = true
)
val showBottomSheet = remember { mutableStateOf(false) }

Box(modifier = modifier.fillMaxSize().background(color = Color.Green)) {
    Button(
        modifier = Modifier.align(Alignment.Center),
        onClick = { showBottomSheet.value = !showBottomSheet.value }
    ) {
        Text("CLICK ME")
    }

    if (showBottomSheet.value) {
        ModalBottomSheet(
            onDismissRequest = {}, // 空实现,拒绝任何手动触发的关闭
            sheetState = bottomSheetState, // 修正变量名错误
            shape = RoundedCornerShape(size = 12.dp),
            sheetGesturesEnabled = false, // 禁用拖拽手势
            dragHandle = null,
            modifier = Modifier.fillMaxWidth(),
            properties = ModalBottomSheetProperties(
                shouldDismissOnBackPress = false, // 禁用返回键关闭
                shouldDismissOnClickOutside = false, // 关键:禁止点击外部背景关闭
                isAppearanceLightStatusBars = true
            ),
            containerColor = Color.Red
        ) {
            Box(modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = "BOTTOM SHEET CONTENT",
                    textAlign = TextAlign.Center,
                    modifier = Modifier.align(Alignment.Center).height(100.dp)
                )
            }
        }
    }
}

关键配置说明

  • shouldDismissOnClickOutside = false:这是解决你当前问题的核心,直接禁止点击Sheet外部区域触发关闭
  • sheetGesturesEnabled = false:禁用拖拽Sheet的手势操作
  • shouldDismissOnBackPress = false:禁止通过返回键关闭Sheet
  • onDismissRequest = {}:空实现确保没有其他手动关闭的入口
  • 修正了变量名错误:将使用时的bottomState改为定义的bottomSheetState,避免运行时异常

内容的提问来源于stack exchange,提问作者Youb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 20:33:21