You will need to measure the width of the text in the TextView programmatically, for example:
Rect bounds = new Rect(); textView.getPaint().getTextBounds(textView.getText().toString(), 0, textView.getText().length(), bounds);
Now you can place the colored rectangle behind the TextView and set its width programmatically after measuring the text (I use FrameLayout to put the views on top of each other, but you can use RelativeLayout ):
XML:
<FrameLayout android:layout_width="match_parent" android:layout_height="match_parent"> <View android:id=" +@id /background" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@color/green" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:breakStrategy="balanced" android:text="@string/long_text" /> </FrameLayout>
code:
Rect bounds = new Rect(); textView.getPaint().getTextBounds(textView.getText().toString(), 0, textView.getText().length(), bounds); View bg = findViewById(R.id.background); gb.getLayoutParams().width = bounds.width();
The code is not verified, but I'm sure you understand.
UPDATE
Perhaps this will be possible without using a second background view , setting the width of the TextView to match bounds.width() , but this will cause a change in the way the text breaks, so you need to be careful not to cause an infinite loop.
source share