【发布时间】:2022-07-07 06:53:57
【问题描述】:
我使用 Jetpack Compose ModalBottomSheetLayout 来全屏显示 BottomSheet。当用户将此底部表滑动到底部以将其关闭时,它会停留在 HalfExpanded 状态。然后用户需要再次滑动才能完全关闭它。如何跳过此 HalfExpand 并在第一次滑动时隐藏 BottomSheet。
【问题讨论】:
标签: android-jetpack-compose bottom-sheet
我使用 Jetpack Compose ModalBottomSheetLayout 来全屏显示 BottomSheet。当用户将此底部表滑动到底部以将其关闭时,它会停留在 HalfExpanded 状态。然后用户需要再次滑动才能完全关闭它。如何跳过此 HalfExpand 并在第一次滑动时隐藏 BottomSheet。
【问题讨论】:
标签: android-jetpack-compose bottom-sheet
您可以在rememberModalBottomSheetState函数中使用confirmStateChange参数。
val modalBottomSheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
confirmStateChange = {
it != ModalBottomSheetValue.HalfExpanded
}
)
ModalBottomSheetLayout(
sheetState = modalBottomSheetState,
sheetContent = {
...
}
) {
...
}
【讨论】:
这会向下滑动到半状态并动画到隐藏状态。 这可行,但 UI 有点乱。
@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()
【讨论】:
Compose 1.2-rc03 有解决该问题的方法。
val sheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
skipHalfExpanded = true
)
您可以使用“skipHalfExpanded”属性将其完全展开。
【讨论】: