我正在尝试在 Jetpack Compose 中制作一个非常简单的 ModalBottomSheet。我想用 ModalBottomSheet 实现两个主要功能,即 - 对于高度 - 当我单击 Scaffold 的操作时
我正在尝试在 Jetpack Compose 中制作一个非常简单的 ModalBottomSheet。我想用 ModalBottomSheet 实现两个主要功能:
我试过这段代码
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScaffoldWithBottomSheet() {
val sheetState = rememberModalBottomSheetState(
skipPartiallyExpanded = false
)
val scope = rememberCoroutineScope()
var showBottomSheet by remember { mutableStateOf(false) }
Scaffold(
topBar = {
TopAppBar(
title = {
Text(text = "Hello")
},
actions = {
IconButton(onClick = {
showBottomSheet = true
scope.launch {
// Explicitly set the bottom sheet to partially expanded (70%)
sheetState.show()
sheetState.partialExpand()
}
}) {
Icon(imageVector = Icons.Default.MoreVert, contentDescription = null)
}
}
)
}
) { innerPadding ->
Column(
modifier = Modifier.padding(innerPadding)
) {
// Main content goes here
}
if (showBottomSheet) {
ModalBottomSheet(
modifier = Modifier.fillMaxWidth(),
onDismissRequest = {
showBottomSheet = false
},
sheetState = sheetState
) {
// Custom behavior to mimic 70% height when partially expanded
Box(
modifier = Modifier
.fillMaxWidth()
.height(
if (sheetState.currentValue == SheetValue.PartiallyExpanded)
(LocalConfiguration.current.screenHeightDp * 0.7f).dp
else
LocalConfiguration.current.screenHeightDp.dp
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Button(onClick = {
scope.launch {
sheetState.hide()
}.invokeOnCompletion {
if (!sheetState.isVisible) {
showBottomSheet = false
}
}
}) {
Text(text = "Hide")
}
Text(text = "Swipe up to expand fully!")
}
}
}
}
}
}
我使用这段代码得到的行为是,当我点击按钮时,它会打开到默认高度,然后当我向上滚动它时,它会打开到高度的 70%,当我再次向上滚动它时,它会打开 100% 的高度。但我不需要它。我希望,当我点击按钮时,它必须直接覆盖到高度的 70%。我谦虚地请求大家帮助我解决这个问题。