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

Jetpack Compose TextField文本对齐异常且被截断问题求助

问题

设置了一个方形TextField输入框,希望在其中显示单个24sp的字符。外层Box尺寸设为52.dp,空间充足,但字符却下移并被截断。代码及效果截图如下:

var inputChar by remember {
    mutableStateOf("2")
}

Box(
    modifier = Modifier
        .size(52.dp)
        .border(
            width = 1.dp,
            color = Color.Black,
            shape = RoundedCornerShape(5.dp)
        )
        .aspectRatio(1f)
) {
    TextField(
        value = inputChar,
        onValueChange = { newText ->
            inputChar = newText
        },
        keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
        modifier = Modifier.fillMaxSize(),
        textStyle = LocalTextStyle.current.copy(textAlign = TextAlign.Center)
            .merge(TextStyle(fontSize = 24.sp)),
        colors = TextFieldDefaults.textFieldColors(
            backgroundColor = Color.LightGray,
            cursorColor = Color.Black,
            focusedIndicatorColor = Color.Transparent,
            unfocusedIndicatorColor = Color.Transparent
        ),
        shape = RoundedCornerShape(5.dp),
        singleLine = true,
    )
}

截断的文本

解决方案

问题源于TextField默认的内边距和行高设置,通过以下调整即可解决:

  • 移除TextField默认内边距:给TextField的modifier添加padding(0.dp),避免内边距挤压文本空间
  • 统一行高与字体大小:在textStyle中设置lineHeight = 24.sp,消除文本垂直偏移
  • 限制输入长度:在onValueChange中过滤文本,确保仅保留单个字符,匹配需求场景

修改后的完整代码:

var inputChar by remember {
    mutableStateOf("2")
}

Box(
    modifier = Modifier
        .size(52.dp)
        .border(
            width = 1.dp,
            color = Color.Black,
            shape = RoundedCornerShape(5.dp)
        )
        .aspectRatio(1f)
) {
    TextField(
        value = inputChar,
        onValueChange = { newText ->
            inputChar = newText.take(1)
        },
        keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
        modifier = Modifier
            .fillMaxSize()
            .padding(0.dp),
        textStyle = LocalTextStyle.current.copy(
            textAlign = TextAlign.Center,
            fontSize = 24.sp,
            lineHeight = 24.sp
        ),
        colors = TextFieldDefaults.textFieldColors(
            backgroundColor = Color.LightGray,
            cursorColor = Color.Black,
            focusedIndicatorColor = Color.Transparent,
            unfocusedIndicatorColor = Color.Transparent
        ),
        shape = RoundedCornerShape(5.dp),
        singleLine = true,
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:42:50