Jetpack Compose 在外部单击时折叠底部工作表

Jon*_*vin 4 android kotlin bottom-sheet android-jetpack-compose android-jetpack-compose-scaffold

我目前通过 a 显示底部工作表BottomSheetScaffold,并希望当用户在底部工作表外部单击时折叠它。有没有办法检测底页之外的点击?

这是我的屏幕BottomSheetScaffold

@ExperimentalMaterialApi
@ExperimentalMaterial3Api
@Composable
fun HomeScreen() {
    val bottomSheetScaffoldState = rememberBottomSheetScaffoldState(
        bottomSheetState = BottomSheetState(BottomSheetValue.Collapsed)
    )
    val coroutineScope = rememberCoroutineScope()

    BottomSheetScaffold(
        scaffoldState = bottomSheetScaffoldState,
        sheetContent = {
            Box(
                Modifier
                    .fillMaxWidth()
                    .fillMaxHeight(0.9f)
            ) {
                Text("Hello from Sheet")
            }
        },
        sheetShape = RoundedCornerShape(
            topStart = Spacing.l,
            topEnd = Spacing.l
        ),
        sheetPeekHeight = LocalConfiguration.current.screenHeightDp.dp * 0.15f,
        sheetBackgroundColor = MaterialTheme.colorScheme.surface,
    ) {
        Scaffold() {
            Button(
                onClick = {
                    coroutineScope.launch {
                        if (bottomSheetScaffoldState.bottomSheetState.isCollapsed) {
                            bottomSheetScaffoldState.bottomSheetState.expand()
                        } else {
                            bottomSheetScaffoldState.bottomSheetState.collapse()
                        }
                    }
                },
            ) {
                Text("Toggle Sheet")
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

这是我想要在底部工作表展开时检测单击的区域的可视化。

在此输入图像描述

Gab*_*tti 12

您可以将pointerInput修饰符添加detectTapGestures到您的Scaffold

   Scaffold( modifier =
        Modifier.pointerInput(Unit) {
            detectTapGestures(onTap = {
                coroutineScope.launch {
                    if (bottomSheetScaffoldState.bottomSheetState.isCollapsed) {
                        bottomSheetScaffoldState.bottomSheetState.expand()
                    } else {
                        bottomSheetScaffoldState.bottomSheetState.collapse()
                    }
                }
            })
    }){
       //.....
    }
Run Code Online (Sandbox Code Playgroud)