如何实现无上下间距的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,需要修改段落缩进逻辑,同时消除默认行间距:
- 把连字符和文本放在同一个段落内,用负首行缩进将连字符拉到左侧,后续行保持正常缩进:
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() }
- 在Text组件中去掉默认上下内边距,并设置精准的行高,消除上下间距:
Text( text = text, modifier = Modifier.padding(vertical = 0.dp), lineHeight = 18.sp // 根据你的字体大小调整,匹配文本实际高度 )
内容的提问来源于stack exchange,提问作者Pascal Okyere Adomako
相关产品推荐
相关产品推荐

