Jetpack Compose Material3中BottomSheetLayout的替代实现方案咨询
在Compose Material3 1.0.0-beta03中实现BottomSheet效果的替代方案
目前Material3 1.0.0-beta03确实没有内置BottomSheetLayout或BottomSheetScaffold,但可以通过以下两种方式实现近似效果,无需依赖旧的androidx.compose.material库:
1. 使用ModalBottomSheetDialog(模态场景)
Material3提供了ModalBottomSheetDialog,可以实现带拖拽交互的模态底部弹窗,这是官方推荐的替代方案之一:
var showBottomSheet by remember { mutableStateOf(false) } val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false) val coroutineScope = rememberCoroutineScope() // 触发按钮 Button(onClick = { showBottomSheet = true }) { Text("打开底部面板") } // 模态底部弹窗 if (showBottomSheet) { ModalBottomSheetDialog( onDismissRequest = { showBottomSheet = false }, sheetState = sheetState, properties = DialogProperties(usePlatformDefaultWidth = false) ) { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Text("Material3 模态底部面板", fontSize = 18.sp, modifier = Modifier.padding(bottom = 16.dp)) // 自定义内容区域 repeat(5) { Text("列表项 ${it + 1}", modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) } Button( onClick = { coroutineScope.launch { sheetState.hide() }.invokeOnCompletion { if (!sheetState.isVisible) showBottomSheet = false } }, modifier = Modifier.align(Alignment.End) ) { Text("关闭") } } } }
2. 自定义可拖拽底部面板(非模态场景)
如果需要非模态、可自由拖拽交互的底部面板,可以结合Draggable和offset实现,完全适配Material3样式:
val sheetHeight = 350.dp val sheetOffset = remember { mutableStateOf(sheetHeight) } val coroutineScope = rememberCoroutineScope() Box(modifier = Modifier.fillMaxSize()) { // 主内容区域 Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Button(onClick = { coroutineScope.launch { sheetOffset.value = 0.dp } }) { Text("拉起底部面板") } } // 自定义底部面板 Column( modifier = Modifier .fillMaxWidth() .height(sheetHeight) .offset(y = sheetOffset.value) .background(MaterialTheme.colorScheme.surface, shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)) .draggable( orientation = Orientation.Vertical, state = rememberDraggableState { delta -> sheetOffset.value = max(0.dp, min(sheetHeight, sheetOffset.value + delta.dp)) } ) .padding(16.dp) ) { // 顶部拖拽指示器 Box( modifier = Modifier .size(40.dp, 4.dp) .align(Alignment.CenterHorizontally) .background(MaterialTheme.colorScheme.onSurface.copy(alpha = 0.3f), shape = RoundedCornerShape(2.dp)) ) Text("自定义可拖拽底部面板", fontSize = 18.sp, modifier = Modifier.padding(top = 16.dp)) // 自定义内容 repeat(6) { Text("内容项 ${it + 1}", modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) } } }
这两种方案都完全基于Material3组件和API,不需要引入旧的material库,可以满足大部分底部面板的使用场景。
内容的提问来源于stack exchange,提问作者Eynnzerr
相关产品推荐
相关产品推荐

