Material3自定义TopAppBar高度:解决标题文本垂直居中问题
解决Material3 TopAppBar自定义高度后标题不垂直居中的问题
在自定义Material3的TopAppBar时,通过modifier.height()修改高度后,标题文本会向上偏移无法垂直居中,但右侧操作图标能正常居中,示例代码如下:
@Composable fun CodTopBar( onSearchIconClicked: () -> Unit ) { TopAppBar( title = { Text( text = "CodSample", fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium, ) }, actions = { IconButton(onClick = onSearchIconClicked) { Icon(imageVector = Icons.Default.Search, contentDescription = "Search") } }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer, actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer, ), modifier = Modifier.height(40.dp) ) }
问题原因
Material3的TopAppBar内部为标题区域设置了默认的上下内边距,当通过modifier.height()强制缩小高度后,默认内边距会挤压标题文本的空间,导致标题向上偏移;而右侧操作图标依赖IconButton的默认布局逻辑,能自适应保持居中。
解决方案
方案一:调整内边距并让标题占满高度居中
修改TopAppBar的contentPadding去除上下内边距,同时给标题Text添加修饰符,让它占满TopAppBar的高度并垂直居中:
@Composable fun CodTopBar( onSearchIconClicked: () -> Unit ) { TopAppBar( title = { Text( text = "CodSample", fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium, modifier = Modifier.fillMaxHeight().verticalAlignment(Alignment.CenterVertically) ) }, actions = { IconButton(onClick = onSearchIconClicked) { Icon(imageVector = Icons.Default.Search, contentDescription = "Search") } }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer, actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer, ), modifier = Modifier.height(40.dp), contentPadding = PaddingValues(horizontal = 16.dp, vertical = 0.dp) ) }
方案二:完全自定义TopAppBar布局
如果需要更灵活的控制,直接用Row组件实现自定义布局,摆脱TopAppBar的默认样式限制:
@Composable fun CodTopBar( onSearchIconClicked: () -> Unit ) { Row( modifier = Modifier .height(40.dp) .fillMaxWidth() .background(MaterialTheme.colorScheme.primaryContainer), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "CodSample", fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onPrimaryContainer, modifier = Modifier.padding(start = 16.dp) ) IconButton(onClick = onSearchIconClicked) { Icon( imageVector = Icons.Default.Search, contentDescription = "Search", tint = MaterialTheme.colorScheme.onPrimaryContainer ) } } }
内容的提问来源于stack exchange,提问作者user2181626
相关产品推荐
相关产品推荐

