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

Jetpack Compose ModalBottomSheet下滑关闭跳过HalfExpanded状态方法

跳过HalfExpanded实现单次下滑关闭全屏ModalBottomSheet

问题根源

ModalBottomSheetLayout默认内置三个状态锚点:Hidden(隐藏)、HalfExpanded(半展开)、Expanded(全展开),手势滑动结束时组件会自动吸附到距离最近的合法锚点,所以下滑时会先停在半展开位置,需要二次滑动才能到隐藏状态。

实现步骤

  • 第一步:初始化ModalBottomSheetState时通过confirmValueChange参数拦截半展开状态,禁止组件在该状态停留
// Material2 版本写法
val bottomSheetState = rememberModalBottomSheetState(
    initialValue = ModalBottomSheetValue.Hidden,
    confirmValueChange = { targetState ->
        // 仅允许隐藏、全展开两个状态生效
        targetState != ModalBottomSheetValue.HalfExpanded
    }
)
  • 第二步:配置BottomSheet内容高度对齐全展开锚点,避免因内容高度不足导致状态判断异常
    因为要实现全屏效果,需要给sheet内容设置满高,同时适配系统栏Insets:
ModalBottomSheetLayout(
    sheetState = bottomSheetState,
    // 可选:调整sheet默认形状、背景色匹配全屏效果
    sheetShape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
    sheetContent = {
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .windowInsetsPadding(WindowInsets.navigationBars)
        ) {
            // 写入全屏BottomSheet的业务内容
        }
    }
) {
    // 主页面内容
}

Material3版本适配

如果使用的是Material3组件库的ModalBottomSheet,仅需要把拦截的状态替换为PartiallyExpanded即可:

// Material3 版本写法
val bottomSheetState = rememberModalBottomSheetState(
    confirmValueChange = { targetState ->
        targetState != SheetValue.PartiallyExpanded
    }
)

配置完成后,用户在全展开状态下滑关闭时,组件会直接跳过中间半展开状态,单次滑动即可吸附到隐藏状态,不会出现卡顿停留的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 02:28:04