Android XML:如何为单个TextView的两行文本添加省略号?
问题描述
我正在设计一个XML界面,不想使用两个TextView,而是希望用一个TextView通过\n分隔两行文本。但当前问题是,当两行(至少第一行)文本过长时,需要显示省略号。请问有没有无需新建TextView的解决办法?
原XML代码:
<TextView android:id="@+id/____" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginHorizontal="10dp" android:layout_marginBottom="10dp" android:ellipsize="end" android:textColor="@color/black" android:textSize="16sp" app:layout_constraintBottom_toTopOf="@+id/_____" app:layout_constraintEnd_toStartOf="@+id/_____" app:layout_constraintStart_toEndOf="@id/startLocationPin" app:layout_constraintTop_toTopOf="parent" tools:text="Line 1\nLine 2" />
解决办法
方法1:默认多行截断(简单XML配置)
如果接受“文本整体超过两行时,在最后一行末尾显示省略号”,只需给TextView添加android:maxLines="2"属性即可,修改后的XML:
<TextView android:id="@+id/____" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginHorizontal="10dp" android:layout_marginBottom="10dp" android:ellipsize="end" android:maxLines="2" android:textColor="@color/black" android:textSize="16sp" app:layout_constraintBottom_toTopOf="@+id/_____" app:layout_constraintEnd_toStartOf="@+id/_____" app:layout_constraintStart_toEndOf="@id/startLocationPin" app:layout_constraintTop_toTopOf="parent" tools:text="Line 1 is very long text that will be truncated\nLine 2" />
注意:这种方式下,如果第一行过长,会自动换行到第二行,最终在第二行末尾显示省略号,而非第一行单独截断。
方法2:代码手动处理每行截断(精准控制)
如果需要第一行和第二行各自独立截断(每行过长时自身末尾显示省略号),可以通过代码手动拆分并处理文本:
val textView = findViewById<TextView>(R.id.____) val originalText = "Line 1 is very long text that needs truncation\nLine 2 may also be long" val lines = originalText.split("\n") val paint = textView.paint // 计算TextView的可用宽度(减去左右内边距) val maxLineWidth = textView.width - textView.paddingStart - textView.paddingEnd // 处理第一行 val truncatedLine1 = if (paint.measureText(lines[0]) > maxLineWidth) { val endIndex = paint.breakText(lines[0], true, maxLineWidth.toFloat(), null) lines[0].substring(0, endIndex) + "..." } else { lines[0] } // 处理第二行(如果存在) val truncatedLine2 = if (lines.size > 1) { if (paint.measureText(lines[1]) > maxLineWidth) { val endIndex = paint.breakText(lines[1], true, maxLineWidth.toFloat(), null) lines[1].substring(0, endIndex) + "..." } else { lines[1] } } else { "" } // 设置处理后的文本 textView.text = "$truncatedLine1\n$truncatedLine2"
注意:要在TextView布局完成后执行这段代码(比如在view.post {}中),否则无法获取到正确的宽度值。
内容的提问来源于stack exchange,提问作者Anon
相关产品推荐
相关产品推荐

