0

I have TextView which contains text. It has background:

    <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"/>

Now, a background is wrapping whole text. I want it to wrap each line individually. Now I am getting the result which is shown on the left of the image. I want to achieve the result which is on the right.

enter image description here

I would create several TextViews with separate backgrounds but TextView shows dynamic text which makes this solution not so good.

My question: how to wrap TextView's each line with background?

Joe Rakhimov
  • 4,713
  • 9
  • 51
  • 109

1 Answers1

2

You can use SpannableString

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

if you want the entire string to highlight

 str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, str.length(), 0);
Amrutha Saj
  • 1,408
  • 16
  • 35