9

I am trying to set a background in a TextView using Html.fromHtml(). In particulare, I want to set the background on the first word.

I have used the following code:

Html.fromHtml("<font color='red'>("+someText+")</font>");

and it is executing successfully with text color. However I want to change the background color.

How can I do this?

1
  • <font color> itself no longer works! What gives??! Commented Dec 30, 2019 at 16:03

9 Answers 9

8

Try this:

TextView TV = (TextView) findViewById(R.id.mytextview01);

Spannable wordtoSpan = new SpannableString("hello hi. how are you?");        

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
wordtoSpan.setSpan(new BackgroundColorSpan(Color.RED), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(wordtoSpan);

This is to set both text and background color (the latter with BackgroundColorSpan).

Sign up to request clarification or add additional context in comments.

3 Comments

No your edited code also not fulfill @PratikButani requirement. i have tested it.
But he asks to change text part background color. Please see his comments in my thread.
@SanketKachhela You are right but it is not working while i am binding data in adapter of GridView.
5

Android officially doesn't support the background coloring of text via HTML but I've found a workaround.

String str = "<span style=\"background-color:#f3f402;\">" + TEXT TO HIGHLIGHT + "</span>";

textView.setText(Html.fromHtml(str, Html.FROM_HTML_MODE_LEGACY));

But, however, the above code only works for Nougat (API 24) and above. So, you'll have to manage the HTML in different Android versions like:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    String str = "<span style=\"background-color:#f3f402;\">" + TEXT TO HIGHLIGHT + "</span>";
    textView.setText(Html.fromHtml(str, Html.FROM_HTML_MODE_LEGACY));
} else {
    String str = "<font color='#f3f402'>" + TEXT TO HIGHLIGHT + "</font>";
    textView.setText(Html.fromHtml(str));
}

You can find more about the HTML tags supported in Android from here:

Comments

3
TextView tv=((TextView)findViewById(R.id.textView));
Spannable word=new SpannableString("HELLO SIDDHARTH");
word.setSpan(new BackgroundColorSpan(Color.BLUE), 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(word);

1 Comment

Its work in simple TextView but not working while binding TextView in GridView
2

For me the best solution was to use HtmlCompat which is now officially integrated in Android X GoogleHtmlCompat. Thereby you can use it directly from API 24, for earlier API versions you can use HtmlCompat library by adding it to your gradle script. HtmlCompat provides more tags and as well some inline styles (text-align, color, background, background-color, text-decoration).

To set a background color of a String in a TextView you can use the following:

String html = "<span style='background-color: #dff0d8;'>"+someText+"</span>"

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY));
} else {
    textView.setText(HtmlCompat.fromHtml(this.getContext(), html, HtmlCompat.FROM_HTML_MODE_LEGACY));
}

5 Comments

OK, but how to use the official Google Android X HtmlCompat in a project targeted at, say, API 26?
Simply by using "Html.fromHtml(...);". All the functionality from HtmlCompat is now included in Html. You don't need to include another library (HtmlCompat) if you only target APIs higher than API 24.
@Phlip I can't confirm this. For me everything still works fine. Do you have an example? On which android version?
It started working. My tiny experiment with "yo <span style='background-color: blue;'>dude</span>" failed, but my production code with a huge blob of generated HTML worked. Go figure...
no need for if else here HtmlCompat.fromHtml does the checking internally
1

There is no support in Html.fromHtml() for background colors. You will need to set up a BackgroundColorSpan yourself.

For example, this sample project highlights search terms using a background color. The key method is:

  private void searchFor(String text) {
    TextView prose=(TextView)findViewById(R.id.prose);
    Spannable raw=new SpannableString(prose.getText());
    BackgroundColorSpan[] spans=raw.getSpans(0,
                                             raw.length(),
                                             BackgroundColorSpan.class);

    for (BackgroundColorSpan span : spans) {
      raw.removeSpan(span);
    }

    int index=TextUtils.indexOf(raw, text);

    while (index >= 0) {
      raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
          + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      index=TextUtils.indexOf(raw, text, index + text.length());
    }

    prose.setText(raw);
  }

It first uses getSpans() and removeSpan() to get rid of previous search results, before creating new BackgroundColorSpan instances and applying them via setSpan().

Comments

0

The docs for the Html class indicate that it does not support all tags (and also, I'm assuming, attributes). Looking at the source code (line 653) shows that the only attributes it supports for the font tag are "color" and "face".

1 Comment

The other answers do this, I was just pointing out why it doesn't work and to highlight that you need to be careful when using this class.
0

Sorry,

You can do this from XML layout :

<TextView
android:background="#0000FF"
android:textColor="#FFFFFF" />

or from code

TextView tv1=(TextView) findViewById(R.id.tv1);

tv1.setTextColor(Color.RED);
tv1.setBackgroundColor(Color.GREEN);

4 Comments

I want for background ;(
you are right dude and thanks for edit.. but i want to backgroud for first word only. i mean in "Hello World" i want to bg for "Hello" only.
Okk Dont worry. Thanks for your efforts. @SatyakiMukherjee
Its was just not working in Adapter of GridView. I have tried with sample and that is working but not work while binding.
0

You can try this:

LinearLayout linearLayout= (LinearLayout) findViewById(R.id.department_content);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT);

TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
String head="<font color=#f5971b>"+this text with color+"</font>";
tv.setText(Html.fromHtml(head));
tv.append("\n"+"thid text in new line");
tv.setTextColor(Color.parseColor("#000000"));

linearLayout.addView(tv);

1 Comment

You are always using code snippets for normal code. Code Snippets are only supposed to be used for HTML or javascript or other code which can be run in the browser. You cannot run Java in the browser. Use normal code blocks in the future... I will edit your answer for you this time and fix the formatting etc, but please don't do this anymore in the future. This isn't the first time I told you about this...
0

I think that one solution is use the library:

https://github.com/Pixplicity/HtmlCompat

If you generate the html text with webs like: https://wordhtml.com/

<string name="html_text">
<![CDATA[
<p><span style="color: #0000ff;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. </span></p>
<p><span style="background-color: #ffff99;">Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec</span></p>
]]>
</string>

Simply something like this would work:

String htmltext = getString(R.string.html_text).replaceAll(": ",":");
Spanned fromHtml = HtmlCompat.fromHtml(getContext(), htmltext, 0);  
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(fromHtml);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.