I have such layout (I\'ve removed some attributes, cause they really doesn\'t matter, full demo project is here):
You'll need to measure the width of the text in TextView
programatically, like so:
Rect bounds = new Rect();
textView.getPaint().getTextBounds(textView.getText().toString(), 0, textView.getText().length(), bounds);
Now, you can place a colored rectangle behind the TextView
, and set its width programatically after measuring the text (I'm using FrameLayout
to put the Views one on top of the other, but you can use RelativeLayout
as well):
XML:
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();
Code is untested, but I'm sure you get the point.
UPDATE
It may be possible to do this without using a second background view
, by setting the TextView
width to match bounds.width()
, but this trigger a change in how the text breaks, so need to be careful not to cause an infinite loop.