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

如何实现无上下间距的AnnotatedString列表项文本缩进对齐?

解决AnnotatedString列表项文本与连字符对齐及上下间距问题

我正在使用AnnotatedString展示列表项,每个项包含一个连字符,并通过ParagraphStyle实现文本缩进,代码如下:

val text = buildAnnotatedString {
    append("-")
    pushStyle(
        ParagraphStyle(
            textIndent = TextIndent(
                firstLine = 20.sp,
                restLine = 20.sp
            ),
        )
    )
    append("This is a long text i want indented with the space at the top or bottom.")
    pop()
}

但当前文本上下存在间距/内边距,无法与连字符对齐(见下图):
文本与连字符未对齐的示意图

请问如何实现无上下间距的文本缩进?


方案1:用Row布局替代AnnotatedString样式(推荐)

直接通过Row组件包裹连字符和文本,精准控制对齐和间距,完全避开段落样式带来的问题:

Row(verticalAlignment = Alignment.CenterVertically) {
    Text("-")
    Text(
        text = "This is a long text i want indented with the space at the top or bottom.",
        modifier = Modifier.padding(start = 20.sp.toDp())
    )
}

这种方式布局逻辑更直观,连字符和文本的垂直对齐完全由Row的verticalAlignment控制,上下间距可以通过Text的modifier直接设置为0。

方案2:调整AnnotatedString的段落样式

如果必须使用AnnotatedString,需要修改段落缩进逻辑,同时消除默认行间距:

  1. 把连字符和文本放在同一个段落内,用负首行缩进将连字符拉到左侧,后续行保持正常缩进:
val text = buildAnnotatedString {
    pushStyle(
        ParagraphStyle(
            textIndent = TextIndent(
                firstLine = (-16).sp, // 负缩进值根据连字符的宽度调整,确保连字符完全左移
                restLine = 20.sp
            )
        )
    )
    append("- This is a long text i want indented with the space at the top or bottom.")
    pop()
}
  1. 在Text组件中去掉默认上下内边距,并设置精准的行高,消除上下间距:
Text(
    text = text,
    modifier = Modifier.padding(vertical = 0.dp),
    lineHeight = 18.sp // 根据你的字体大小调整,匹配文本实际高度
)

内容的提问来源于stack exchange,提问作者Pascal Okyere Adomako

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:47:17