如何禁用 Material3 ModalBottomSheet 拖拽并保留内部滚动?
可以。如果项目使用的 Material3 版本提供 sheetGesturesEnabled 参数,在 ModalBottomSheet 上设置 sheetGesturesEnabled = false,就能关闭 sheet 自身的拖拽。内部仍可使用 LazyColumn 或 Modifier.verticalScroll() 滚动内容。该参数控制 bottom sheet 的手势交互,默认值为 true。ModalBottomSheet API 文档
为什么 confirmValueChange 仍会产生回弹
confirmValueChange 用于确认或否决状态切换。原代码中的 newValue != SheetValue.Hidden 会拒绝切换到 Hidden,但拖拽时 sheet 的位置仍会变化,所以向下移动后会回弹。
skipPartiallyExpanded = true 控制是否跳过 PartiallyExpanded 状态,dragHandle = null 用于移除拖拽指示条。这两个设置都不能关闭 sheet 的拖拽行为。参数与状态说明
设置 sheetGesturesEnabled 并保留列表滚动
先确认当前依赖中的 ModalBottomSheet 函数签名包含 sheetGesturesEnabled,再将它设为 false。列表继续使用自己的滚动组件,无需额外拦截触摸事件。
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NonDraggableSheet(
onDismissRequest: () -> Unit
) {
val sheetState = rememberModalBottomSheetState(
skipPartiallyExpanded = true
)
ModalBottomSheet(
sheetState = sheetState,
onDismissRequest = onDismissRequest,
sheetGesturesEnabled = false,
dragHandle = null
) {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 480.dp)
) {
items(count = 100) { index ->
Text(
text = "Item $index",
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
}
}
}
示例中的 480.dp 是列表高度上限,可以按页面布局调整。内容超过可用高度时,LazyColumn 会自行处理滚动,不要再给它叠加 verticalScroll()。
示例只需禁用拖拽,因此没有用 confirmValueChange 否决 Hidden 状态。手势开关会传递给底层 bottom sheet 的手势处理逻辑。Material3 实现
版本和关闭行为需要单独处理
如果编译器提示找不到 sheetGesturesEnabled,请检查导入是否为 androidx.compose.material3.ModalBottomSheet,并确认项目实际解析到的 Material3 版本是否提供该参数。原问题没有给出依赖版本,不能直接判断现有项目是否支持这种写法。
如果当前版本没有这个参数,优先升级到提供该 API 且与项目兼容的版本。无法升级时,需要保留自定义组件,或维护一份适配当前版本的实现,同时处理直接拖拽和 nested scroll 引起的 sheet 位移。仅靠 confirmValueChange 无法完全禁止拖拽。
禁用拖拽后,仍需分别考虑点击遮罩、按返回键以及程序调用 sheetState.hide() 的行为。如果还要禁止点击遮罩和返回键关闭,可在当前版本支持的前提下,配置 ModalBottomSheetProperties 的 shouldDismissOnClickOutside 和 shouldDismissOnBackPress。把 onDismissRequest 写成空回调不能替代这些关闭策略。正常允许关闭时,调用方应在回调中更新显示状态,将 sheet 移出 composition。关闭行为与 properties 说明
备注:内容仅供参考。
