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

Jetpack Compose中Row内BasicTextField文本无法完全居中如何解决

问题原因

  • 水平居中无效:TextAlign.Center 仅控制文本在自身可绘制区域的水平对齐,当前 BasicTextField 宽度默认包裹文本内容,没有多余空间让水平居中规则生效。
  • 垂直居中无效:Compose 文本绘制默认开启 includeFontPadding,会给文本上下添加系统自带的字体边距,同时没有配置文本在输入框固定高度内的垂直对齐规则,导致文本垂直偏移。

修复方案

方案1:通过文本样式配置(适合固定高度场景)

Row(
    verticalAlignment = Alignment.CenterVertically,
    horizontalArrangement = Arrangement.Center
) {
    BasicTextField(
        modifier = Modifier
            .height(40.dp)
            .width(120.dp) // 按需设置宽度,也可使用fillMaxWidth等配置
            .align(Alignment.CenterVertically),
        value = "Hello",
        onValueChange = {},
        singleLine = true,
        textStyle = LocalTextStyle.current.copy(
            textAlign = TextAlign.Center,
            lineHeight = 40.sp, // 行高和输入框高度保持一致
            includeFontPadding = false // 关闭系统默认字体边距
        ),
    )
}

方案2:通过decorationBox配置(通用场景,适配任意高度)

利用 BasicTextField 的 decorationBox 参数手动控制文本的对齐规则,不需要手动匹配行高和输入框高度:

Row(
    verticalAlignment = Alignment.CenterVertically,
    horizontalArrangement = Arrangement.Center
) {
    BasicTextField(
        modifier = Modifier
            .height(40.dp)
            .width(120.dp)
            .align(Alignment.CenterVertically),
        value = "Hello",
        onValueChange = {},
        singleLine = true,
        textStyle = LocalTextStyle.current.copy(
            textAlign = TextAlign.Center,
            includeFontPadding = false
        ),
        decorationBox = { innerTextField ->
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                innerTextField()
            }
        }
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:36:07