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

Jetpack Compose中OutlinedTextField换行时出现异常间距问题

Jetpack Compose OutlinedTextField换行间距异常解决方法

问题出在你给textStyle和placeholder的Text组件设置了极小的固定行高:lineHeight = TextUnit(1.0F, TextUnitType.Sp)。这个数值远小于headlineMedium默认的行高,直接导致了文本换行后出现异常间距。

解决步骤:

  • 直接移除手动设置的lineHeight,复用MaterialTheme.typography.headlineMedium的默认行高(Material Design规范已经优化过这个样式的行高,适配常规排版需求)
  • 如果需要自定义行高,优先用基于字体大小的Em单位设置合理数值,比如1.2F倍的字体高度,不要用极小的固定Sp值

修改后的代码:

OutlinedTextField(
    value = viewModel.notes.value,
    onValueChange = { viewModel.notes.value = it },
    maxLines = 2,
    minLines = 2,
    textStyle = MaterialTheme.typography.headlineMedium,
    placeholder = {
        Text(
            text = "Notes (Optional)",
            style = MaterialTheme.typography.headlineMedium
        )
    },
    modifier = Modifier
        .fillMaxWidth(),
    shape = RoundedCornerShape(6.dp),
    colors = TextFieldDefaults.colors(
        unfocusedContainerColor = Color.White,
        focusedContainerColor = Color.White,
        focusedIndicatorColor = borderColor,
        unfocusedIndicatorColor = borderColor,
    )
)

自定义行高的可选方案:

如果想要稍微紧凑的行间距,可以用Em单位设置(基于字体大小自适应,避免固定值的布局错乱):

textStyle = MaterialTheme.typography.headlineMedium.copy(
    lineHeight = TextUnit(1.2F, TextUnitType.Em)
),
placeholder = {
    Text(
        text = "Notes (Optional)",
        style = MaterialTheme.typography.headlineMedium.copy(
            lineHeight = TextUnit(1.2F, TextUnitType.Em)
        )
    )
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 07:53:21