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

Jetpack Compose TextField设44.dp高度后文本错位问题求助

解决Compose TextField设置固定高度44.dp后文本错位问题

问题原因

直接给TextField强制设置.height(44.dp)会覆盖其默认内部布局约束,TextField自带的上下contentPadding(默认各16.dp)加上文本高度,会超出固定高度限制,导致内部文本区域被挤压偏移。

解决方案

通过调整contentPadding适配固定高度,同时保留内部元素的正确对齐,修改后的代码如下:

@Composable
fun TestingTextInput(number: Int, modifier: Modifier = Modifier){
    var text by remember { mutableStateOf("") }
    var isFocused by remember { mutableStateOf(false) }
    Box(modifier = modifier) {
        TextField(
            value = text,
            singleLine = true,
            onValueChange = { text = it },
            leadingIcon = { 
                Text(
                    text = "$number:", 
                    color = Color.Gray, 
                    fontSize = 15.sp, 
                    textAlign = TextAlign.End, 
                    modifier = Modifier.width(24.dp)
                )
            },
            modifier = Modifier
                .onFocusChanged { isFocused = it.isFocused }
                .fillMaxWidth()
                .height(44.dp), // 保留固定高度
            contentPadding = PaddingValues(
                top = 12.dp, // 调整上下内边距,让文本垂直居中
                bottom = 12.dp,
                start = 16.dp,
                end = 16.dp
            ),
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent,
                focusedIndicatorColor = Light_Blue,
                unfocusedIndicatorColor = Color.Gray,
                disabledIndicatorColor = Color.Gray
            ),
            textStyle = TextStyle(
                fontFamily = robotoFamily, 
                fontSize = 15.sp, 
                fontWeight = FontWeight.Normal
            )
        )
    }
}

关键调整点

  1. 自定义contentPadding:将上下内边距设为12.dp,配合15.sp的文本高度(约20.dp),总高度刚好为12+20+12=44.dp,完全适配固定高度,避免文本挤压错位。
  2. 保留fillMaxWidth:确保TextField宽度自适应父布局,避免横向布局异常。

如果不需要严格固定高度,也可以用.heightIn(min = 44.dp)替代.height(44.dp),既保证最小高度,又允许内部布局有足够空间,从根源上避免挤压问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:02:10