Android Jetpack Compose中Row组件子元素无法垂直居中问题求助
问题解决:Row垂直居中无效果的原因及修复
你的代码里Row默认高度是wrapContentHeight,而子元素都是Text,它们的高度本身一致,所以设置verticalAlignment = Alignment.CenterVertically后视觉上没有变化——因为本来就处于垂直方向的中间位置。
要看到垂直居中的效果,你需要给Row设置一个大于子元素高度的可用空间,比如通过Modifier.fillMaxHeight()让Row占满屏幕高度,或者设置固定高度比如Modifier.height(200.dp)。
修复后的代码示例:
@Composable fun HorizontalScreen(){ Row( modifier = Modifier.fillMaxWidth().fillMaxHeight(), // 新增fillMaxHeight()让Row占满垂直空间 horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { Text(text = "Text 1") Text(text = "Text 2") Text(text = "Text 3") Text(text = "Text 4") } } @Preview(showBackground = true, showSystemUi = true) @Composable fun HorizontalScreenPreview(){ HorizontalScreen() }
如果想更直观看到布局范围,还可以给Row加背景色:
modifier = Modifier.fillMaxWidth().fillMaxHeight().background(Color.LightGray)
这样就能清晰看到四个Text在Row的垂直中间位置了。
内容的提问来源于stack exchange,提问作者Patrick Renaud
相关产品推荐
相关产品推荐

