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

如何解决Jetpack Compose固定高度TextField文本显示错位问题

问题根因

Jetpack Compose 自带的 TextField 组件默认内置了上下内边距,用来承载输入指示器、标签、占位符等附属元素,默认最小高度远高于你设置的28dp。你直接通过Modifier.height()强行限制高度时,内置的内边距会挤压文本的绘制区域,最终导致文本显示错位。

解决方案

修改TextField的contentPadding参数,自定义组件的内边距,取消默认的多余上下留白,即可适配你需要的小尺寸高度,修正后的参考代码如下:

Row(
    verticalAlignment = Alignment.CenterVertically,
    modifier = Modifier
        .fillMaxWidth()
        .background(color = LightGray20, shape = RoundedCornerShape(6.dp))
        .padding(6.dp)
) {
    TextField(
        modifier = Modifier
            .width(80.dp)
            .height(28.dp),
        value = product.quantity.toString(),
        onValueChange = {
            it.toDoubleOrNull()?.let { value -> quantityChangeHandler(product, value) }
        },
        textStyle = LocalTextStyle.current.copy(textAlign = TextAlign.End, fontSize = 16.sp),
        maxLines = 1,
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Number,
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = { localFocusManager.clearFocus() }
        ),
        shape = RoundedCornerShape(8.dp),
        colors = TextFieldDefaults.textFieldColors(
            focusedIndicatorColor = Color.Transparent,
            unfocusedIndicatorColor = Color.Transparent,
            disabledIndicatorColor = Color.Transparent,
        ),
        // 新增自定义内边距,可根据实际字体大小微调垂直边距
        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 3.dp)
    )
    Text(
        text = description,
        fontSize = 16.sp,
        maxLines = 1,
        modifier = Modifier.padding(start = 2.dp)
    )
}

如果需要更灵活的自定义样式,也可以使用无默认样式的BasicTextField组件实现,它没有内置内边距,不会出现文本被挤压的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:24:03