Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView with background color only on the text itself

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 :)

like image 581
sockeqwe Avatar asked Jun 08 '13 16:06

sockeqwe


People also ask

How do I add background color to TextView?

To change the background color of TextView widget, set the background attribute with required Color value. You can specify color in rgb , argb , rrggbb , or aarrggbb formats. The background color is applied along the width and height of the TextView.

What is text view?

A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor, however the basic class is configured to not allow editing.

How do I assign text to TextView?

Set The Text of The TextView You can set the text to be displayed in the TextView either when declaring it in your layout file, or by using its setText() method. The text is set via the android:text attribute. You can either set the text as attribute value directly, or reference a text defined in the strings.

Which of the following is properties of TextView?

Properties of TextView in Android. android:id-ID is an attribute used to define a TextView uniquely. android: layout_height- Height is the attribute which is used to set the height of the TextView.


1 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

like image 145
lelloman Avatar answered Oct 16 '22 17:10

lelloman