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

如何在Jetpack Compose中使用AnnotatedString设置行高

解决AnnotatedString中SpanStyle无法设置行高的问题

在Jetpack Compose里,SpanStyle确实没有提供行高配置项,因为行高属于段落级样式,而非字符级样式。你可以根据需求选择以下方案:

方案1:给Text组件设置全局行高

如果所有文本只需要统一行高,直接给外层Text组件设置lineHeight参数即可,AnnotatedString内的所有Span都会继承这个行高:

val annotatedString = buildAnnotatedString {
    withStyle(SpanStyle(fontSize = 24.sp)) {
        append("1.26 ")
    }
    withStyle(SpanStyle(fontSize = 14.sp, color = Color.Gray)) {
        append("Kilowatts")
    }
}

Text(
    text = annotatedString,
    lineHeight = 32.sp // 全局行高
)

方案2:用ParagraphStyle设置段落级行高

如果需要不同段落有不同行高,可以使用支持lineHeight配置的ParagraphStyle(段落样式),把需要单独设置行高的文本包裹在withStyle(ParagraphStyle(...))中:

val annotatedString = buildAnnotatedString {
    // 第一段文本,自定义行高
    withStyle(ParagraphStyle(lineHeight = 32.sp)) {
        withStyle(SpanStyle(fontSize = 24.sp)) {
            append("1.26 ")
        }
    }
    // 第二段文本,另一个行高
    withStyle(ParagraphStyle(lineHeight = 20.sp)) {
        withStyle(SpanStyle(fontSize = 14.sp, color = Color.Gray)) {
            append("Kilowatts")
        }
    }
}

Text(text = annotatedString)

方案3:同一行内不同文本用多Text组件组合

如果是同一行内的不同文本需要不同行高(比如你截图里的数字和单位),更灵活的方式是用Row包裹两个独立的Text组件,分别设置各自的行高:

Row(verticalAlignment = Alignment.CenterVertically) {
    Text(
        text = "1.26",
        fontSize = 24.sp,
        lineHeight = 32.sp
    )
    Spacer(modifier = Modifier.width(4.dp))
    Text(
        text = "Kilowatts",
        fontSize = 14.sp,
        color = Color.Gray,
        lineHeight = 20.sp
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:31:03