Home » Android » android – TextView with background color only on the text itself

android – TextView with background color only on the text itself

Posted by: admin June 15, 2020 Leave a comment

Questions:

How do I implement something like this:

enter image description here

I want to do that within a single TextView. Setting the background color of the TextView will not do the job.

I guess it should be possible with a spannable, but I don’t know how.

In html I would do that:

<html>
<body>
        <span style="background:#CCCCCC;">first line <br /> second long line </span>
</body>
</html>

But i don’t know how to do that on Android.
The very last option would be to split the text into two text view, and set each textviews background color and with/height to wrap_content. But since the text length / count of words can be dynamically, I need to calculate the length of each word etc. There must be a better way 🙂

How to&Answers:

something like this should do the job

String myString = "first line\nsecond long line";
Spannable spanna = new SpannableString(myString);
spanna.setSpan(new BackgroundColorSpan(0xFFCCCCCC),0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);           
myTextView.setText(spanna);

if you like to keep it in html you can use a WebView and load your html there, styling should be easier with css, I think