You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose 如何实现 Text 组件内部文本内容居中

问题原因

你设置的textAlign = TextAlign.Center仅能实现文本在Text组件绘制区域内的水平居中,无法控制垂直方向的对齐规则。你给Text设置了fillMaxHeight(),组件高度和父Row保持一致,Compose的Text组件默认文本顶部对齐,因此会出现垂直方向不居中的问题。

注意:你代码中写的Modifier.align(Alignment.CenterVertically)是控制整个Text组件在父Row容器中的垂直位置,不是控制Text内部文本的对齐规则,因此无法解决内部文本不居中的问题。

解决方案

有两种常用的修复方式:

方案1:添加垂直内容对齐修饰符

给Text的Modifier追加wrapContentHeight(Alignment.CenterVertically),指定文本在Text组件的高度范围内垂直居中即可,修改后的代码如下:

Row(
    modifier = Modifier
        .padding(8.dp)
        .height(30.dp)
        .fillMaxHeight(),
) {
    IconButton(..) {..}
    Spacer(modifier = Modifier.width(4.dp))
    Text(
        text = "Some text",
        textAlign = TextAlign.Center,
        modifier = Modifier
            .fillMaxHeight()
            .wrapContentHeight(Alignment.CenterVertically) // 追加这行
            .border(1.dp, Color.Black, RoundedCornerShape(20))
            .width(120.dp)
            .background(color = Color.White, RoundedCornerShape(20))
            .align(Alignment.CenterVertically)
    )
    Spacer(modifier = Modifier.width(4.dp))
    IconButton(..) {..}
}

方案2:用padding替代固定高度填充

如果不需要Text撑满父组件高度,也可以移除fillMaxHeight(),给Text设置上下对称的padding,让文本自然居中,这种方式实现的样式更适配圆角背景场景:

Text(
    text = "Some text",
    textAlign = TextAlign.Center,
    modifier = Modifier
        .padding(vertical = 6.dp) // 上下对称padding,根据高度调整数值即可
        .border(1.dp, Color.Black, RoundedCornerShape(20))
        .width(120.dp)
        .background(color = Color.White, RoundedCornerShape(20))
        .align(Alignment.CenterVertically)
)

内容的提问来源于stack exchange,提问作者daniyelp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:09:02