我使用 Jetpack Compose ModalBottomSheetLayout 来显示全屏 BottomSheet。当用户将此底部工作表滑动到底部以将其关闭时,它会停留在 HalfExpanded 状态。然后用户需要再次滑动才能完全关闭它。我怎样才能跳过这个 HalfExpand 并在第一次滑动时隐藏 BottomSheet。
Compose 1.2-rc03 有针对该问题的解决方案。
val sheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
skipHalfExpanded = true
)
您可以使用“skipHalfExpanded”属性来完全展开它。
更新
正如this answer中提到的,新版本的Jetpack Compose有一个
skipHalfExpanded
属性来支持这个需求。
旧答案
这会向下滑动到一半状态并动画到隐藏状态。 这可行,但用户界面有点简陋。
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ModalBottomSheetSingleSwipe() {
val coroutineScope: CoroutineScope = rememberCoroutineScope()
val modalBottomSheetState: ModalBottomSheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
)
LaunchedEffect(
key1 = modalBottomSheetState.currentValue,
) {
if (modalBottomSheetState.targetValue == ModalBottomSheetValue.HalfExpanded) {
coroutineScope.launch {
modalBottomSheetState.animateTo(ModalBottomSheetValue.Hidden)
}
}
}
ModalBottomSheetLayout(
sheetState = modalBottomSheetState,
sheetContent = {
Text(
text = "Bottom Sheet Content",
modifier = Modifier
.fillMaxWidth()
.padding(all = 16.dp)
.background(LightGray)
.wrapContentHeight()
.height(200.dp),
)
},
) {
Box(
contentAlignment = Alignment.Center,
) {
TextButton(
onClick = {
coroutineScope.launch {
modalBottomSheetState.animateTo(ModalBottomSheetValue.Expanded)
}
},
) {
Text(text = "Open Bottom Sheet")
}
}
}
}
注:
我们必须使用
modalBottomSheetState.animateTo(ModalBottomSheetValue.Expanded)
而不是 modalBottomSheetState.show()
您可以在
confirmStateChange
函数中使用rememberModalBottomSheetState
参数。
val modalBottomSheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
confirmStateChange = {
it != ModalBottomSheetValue.HalfExpanded
}
)
ModalBottomSheetLayout(
sheetState = modalBottomSheetState,
sheetContent = {
...
}
) {
...
}