Jetpack Compose:Material3 CenterAlignedTopAppBar顶部为何出现大量内边距?
解决Material3 CenterAlignedTopAppBar顶部多余内边距问题
问题现象:使用Material3的CenterAlignedTopAppBar时顶部出现大量内边距,Material2下高度正常为56dp,无论用Column还是Scaffold布局、包裹在Fragment中都存在该问题:

Material3的CenterAlignedTopAppBar默认会自动适配系统状态栏的内边距,这是它和Material2组件的核心差异之一——Material2的TopAppBar不会默认处理状态栏Insets,所以你会看到顶部出现额外的空白区域。
解决方案:禁用默认状态栏内边距处理
直接给CenterAlignedTopAppBar设置windowInsets参数为WindowInsets(0),覆盖默认的Insets行为:
@OptIn(ExperimentalMaterial3Api::class) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return ComposeView(requireContext()).apply { setContent { val uiState = viewModel.uiState.collectAsState() viewModel.setIntent(MapIntent.GetOneOrAll(id)) Column { if (uiState.value.hasToolbar) { CenterAlignedTopAppBar( modifier = Modifier.fillMaxWidth().wrapContentHeight(), title = { Text( text = uiState.value.toolbarTitle ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis, color = colorResource(id = R.color.white) ) }, navigationIcon = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = null, tint = colorResource(id = R.color.white) ) } }, actions = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = null, tint = colorResource(id = R.color.white) ) } }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = colorResource(id = R.color.colorPrimaryDark), ), // 添加此行,禁用默认状态栏内边距 windowInsets = WindowInsets(0) ) } MapView( modifier = Modifier.fillMaxSize(), onMapClick = { viewModel.setIntent(MapIntent.OnClickMap) }, onMarkerClick = { viewModel.setIntent(MapIntent.OnClickMarker(it)) }, cameraPositionState = uiState.value.cameraPositionState, markers = uiState.value.markers ) } } } }
补充说明
如果后续需要手动处理状态栏内边距(比如让页面内容避开状态栏),可以给父布局添加Modifier.statusBarsPadding(),而非依赖TopAppBar的默认Insets处理逻辑。
内容的提问来源于stack exchange,提问作者SomeKoder
相关产品推荐
相关产品推荐

