如何让Jetpack Compose的BottomSheetScaffold横屏时铺满全屏
解决BottomSheetScaffold横屏左右留白问题
问题描述
我希望BottomSheetScaffold在横屏模式下铺满整个屏幕,但它的左右两侧始终留有空白。我已经移除了所有可能的内边距,并且在各处使用了modifier.fillMaxSize,但空白仍然存在。
使用的代码如下:
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TESTApplicationTheme { MyUI() } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun MyUI() { val scaffoldState = rememberBottomSheetScaffoldState() val coroutineScope = rememberCoroutineScope() BottomSheetScaffold( modifier = Modifier.fillMaxSize(), scaffoldState = scaffoldState, sheetContent = { Box(modifier = Modifier.fillMaxSize().background(Color.Blue)) }, sheetDragHandle = null, ) { // app UI Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Text(text = "Rest of the app UI") Button( onClick = { coroutineScope.launch { scaffoldState.bottomSheetState.expand() } }, ) { Text(text = "expand") } } } }
解决方案
问题源于Material3的BottomSheetScaffold默认会给底部弹窗添加水平边距,这是组件的内置行为。只需添加两个参数即可解决:
- 设置
sheetShape = RectangleShape:取消底部弹窗默认的圆角和水平边距 - 可选设置
sheetContainerColor = Color.Transparent:避免默认容器颜色干扰内容显示
修改后的完整代码:
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TESTApplicationTheme { MyUI() } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun MyUI() { val scaffoldState = rememberBottomSheetScaffoldState() val coroutineScope = rememberCoroutineScope() BottomSheetScaffold( modifier = Modifier.fillMaxSize(), scaffoldState = scaffoldState, sheetContent = { Box(modifier = Modifier.fillMaxSize().background(Color.Blue)) }, sheetDragHandle = null, sheetShape = RectangleShape, sheetContainerColor = Color.Transparent ) { // app UI Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Text(text = "Rest of the app UI") Button( onClick = { coroutineScope.launch { scaffoldState.bottomSheetState.expand() } }, ) { Text(text = "expand") } } } }
如果仍存在细微边距,可尝试给BottomSheetScaffold的modifier追加padding(horizontal = 0.dp),不过通常设置sheetShape就能解决问题。
内容的提问来源于stack exchange,提问作者Abdoulito
相关产品推荐
相关产品推荐

