【问题标题】:How to wrap each line of TextView with background?如何用背景包装每一行 TextView?
【发布时间】:2026-01-12 00:05:01
【问题描述】:

我有包含文本的 TextView。它有背景:

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!\nEach line should be wrapped by background not whole text"
    android:textColor="#000000"
    android:textSize="24sp"
    android:background="#FFFF00"
    android:gravity="center_horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:padding="8dp"/>

现在,背景正在包裹整个文本。我希望它单独包装每一行。现在我得到了图像左侧显示的结果。我想达到右边的结果。

我会创建几个具有不同背景的 TextView,但 TextView 会显示动态文本,这使得该解决方案不太好。

我的问题:如何用背景包装 TextView 的每一行?

【问题讨论】:

标签: android textview


【解决方案1】:

你可以使用SpannableString

 SpannableString str = new SpannableString("Highlighted. Not highlighted.");
 str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 11, 0);
 textView.setText(str);

如果您希望整个字符串突出显示

 str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, str.length(), 0);

【讨论】:

  • 感谢您的回答。现在我将尝试这个解决方案)
  • 肯定会对你有所帮助。)