我在 Jetpack Compose 中使用 ModalBottomSheetLayout 组件时遇到问题。这是我的代码:
ModalBottomSheetLayout(
modifier = Modifier.fillMaxSize(),
sheetState = bottomSheetState,
sheetContent = {
...
})
当我调用
bottomSheetState.show()
并立即按下物理后退按钮时,它会导航回上一个屏幕,但 ModalBottomSheetLayout 不会关闭。此时,检查 bottomSheetState.isVisible
将返回 false。根据我的理解,当调用bottomSheetState.show()
时,ModalBottomSheetLayout从底部向上滑动,但bottomSheetState.isVisible直到动画完成才改变。这种情况下应该如何处理back事件呢?
您可以使用
targetValue
代替 isVisible
。
当前交互结束后状态将确定的目标值,如果没有正在进行的交互则为 currentValue。
根据文档,
targetValue
是专门为此用例设计的。如果工作表没有动画,则返回 currentValue
;如果工作表正在进行动画,则返回未来 ModalBottomSheetValue
。
您可以检查是否为
targetValue == ModalBottomSheetValue.Expanded
,因为您想要关闭工作表,如果它正在动画为 Expanded
状态或当前处于 Expanded
状态。
BackHandler {
if (bottomSheetState.targetValue == ModalBottomSheetValue.Expanded) {
scope.launch { bottomSheetState.hide() }
} else {
// TODO: Handle back press
}
}