如何在Jetpack Compose M3中实现带指定Peek Height的全屏Modal Bottom Sheet
使用Jetpack Compose M3实现自定义Peek高度的全屏Modal Bottom Sheet
要实现收起时固定Peek Height、展开时占满屏幕的底部面板,只需要调整ModalBottomSheetState的配置并处理内容布局,具体修改如下:
核心修改点
- 自定义
peekHeight参数指定收起时的面板高度 - 确保内容布局填充全屏,让展开状态下面板占满屏幕
- 正确管理面板的状态切换逻辑
完整代码示例
@Composable fun WeatherScreen(api: YourApiType) { val configuration = LocalConfiguration.current val screenHeight = configuration.screenHeightDp.dp // 获取屏幕高度 val sheetState = rememberModalBottomSheetState( initialValue = SheetValue.PartiallyExpanded, // 默认处于收起(Peek)状态 skipPartiallyExpanded = false, peekHeight = 120.dp // 这里设置你需要的特定Peek Height,比如120dp ) val scope = rememberCoroutineScope() Scaffold { paddingValues -> // 主内容区域,添加padding避免被面板遮挡 WeatherView( api = api, modifier = Modifier.padding(paddingValues) ) ModalBottomSheet( modifier = Modifier.fillMaxSize(), sheetState = sheetState, onDismissRequest = { // 点击外部时回到Peek状态,若要完全隐藏则调用sheetState.hide() scope.launch { sheetState.partialExpand() } }, shape = RoundedCornerShape( topStart = 20.dp, topEnd = 20.dp ), containerColor = Color.White.copy(0.2f), dragHandle = { BottomSheetDefaults.DragHandle( width = 48.dp, height = 5.dp, color = Color.Black.copy(0.3f) ) } ) { // 底部面板内容,设置fillMaxSize确保展开时占满屏幕 BottomSheetContent( modifier = Modifier.fillMaxSize(), onExpandFull = { // 手动触发全屏展开的逻辑(如果需要按钮控制) scope.launch { sheetState.expand() } } ) } } } // 示例BottomSheetContent,可根据需求自定义内容 @Composable fun BottomSheetContent(modifier: Modifier = Modifier, onExpandFull: () -> Unit) { Box(modifier = modifier) { Column( modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text("底部面板内容") Button(onClick = onExpandFull) { Text("展开全屏") } } } }
关键说明
- 自定义Peek高度:通过
rememberModalBottomSheetState的peekHeight参数直接设置收起时的面板高度,这个值可以根据设计需求自由调整。 - 全屏展开:给
BottomSheetContent添加Modifier.fillMaxSize(),当面板切换到Expanded状态时,会自动占满整个屏幕高度。 - 状态控制:
- 拖拽手柄支持用户在Peek状态和全屏状态之间手动切换
- 通过
scope.launch { sheetState.expand() }可以手动触发全屏展开 - 通过
scope.launch { sheetState.partialExpand() }回到Peek状态,若需要完全隐藏面板则调用sheetState.hide()
内容的提问来源于stack exchange,提问作者Andrea Liureta
相关产品推荐
相关产品推荐

