在 Jetpack Compose 中的 ModalBottomSheetLayout 动画期间处理后按

问题描述 投票:0回答:1

我在 Jetpack Compose 中使用 ModalBottomSheetLayout 组件时遇到问题。这是我的代码:

ModalBottomSheetLayout(
modifier = Modifier.fillMaxSize(),
sheetState = bottomSheetState,
sheetContent = {
    ...
})

当我调用

bottomSheetState.show()
并立即按下物理后退按钮时,它会导航回上一个屏幕,但 ModalBottomSheetLayout 不会关闭。此时,检查
bottomSheetState.isVisible
将返回 false。根据我的理解,当调用
bottomSheetState.show()
时,ModalBottomSheetLayout从底部向上滑动,但bottomSheetState.isVisible直到动画完成才改变。这种情况下应该如何处理back事件呢?

kotlin android-jetpack-compose onbackpressed jetpack-compose-modalbottomsheet
1个回答
0
投票

您可以使用

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
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.