92

I am developing an application in which there will be a search screen where user can search for specific keywords and that keyword should be highlighted. I have found Html.fromHtml method.

But I will like to know whether its the proper way of doing it or not.

Please let me know your views on this.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
sunil
  • 9,541
  • 18
  • 66
  • 88
  • check out for an working example. http://javatechig.com/2013/04/07/how-to-display-html-in-android-view/ – Nilanchala Apr 07 '13 at 20:29
  • Possible duplicate of [Is it possible to have multiple styles inside a TextView?](http://stackoverflow.com/questions/1529068/is-it-possible-to-have-multiple-styles-inside-a-textview) – blahdiblah Oct 09 '13 at 18:59

10 Answers10

225

Or far simpler than dealing with Spannables manually, since you didn't say that you want the background highlighted, just the text:

String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
Christopher Orr
  • 110,418
  • 27
  • 198
  • 193
  • 9
    It's worth noting, that Html.fromHtml is slower than SpannableString, because it involves parsing. But for a short text it doesn't matter – Michał Klimczak Dec 08 '12 at 19:01
  • There appears to be another solution at [link](http://stackoverflow.com/questions/1529068/is-it-possible-to-have-multiple-styles-inside-a-textview). See the answer by Legend. – Kenneth Evans Jan 15 '13 at 22:25
  • 1
    Just as a comment, I found I didn't need to pass TextView.BufferType.SPANNABLE and it still worked. Thanks! – James Apr 29 '14 at 13:34
  • 1
    do you know any html editor for arrenging long text for android. for example I am trying to use this site (http://www.html.am/html-editors/html-text-editor.cfm) but if I want to see source it returns color as `` so that android dont change the color. – mehmet Jun 07 '14 at 16:14
  • @mehmet You could presumably just search and replace to change the tags to tags with a "color" attribute. – Christopher Orr Jun 10 '14 at 10:18
  • Clarification for those who wonders how to use specific hex color in html: `text` – Johnny Five Mar 19 '19 at 11:42
  • @JohnnyFive I am trying to change – Mateen Chaudhry Apr 23 '19 at 06:18
44

Using color value from xml resource:

int labelColor = getResources().getColor(R.color.label_color);
String сolorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!!

Html.fromHtml(String.format("<font color=\"#%s\">text</font>", сolorString), TextView.BufferType.SPANNABLE); 
worked
  • 5,762
  • 5
  • 54
  • 79
SergeyA
  • 4,427
  • 1
  • 22
  • 15
13

This can be achieved using a Spannable String. You will need to import the following

import android.text.SpannableString; 
import android.text.style.BackgroundColorSpan; 
import android.text.style.StyleSpan;

And then you can change the background of the text using something like the following:

TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Your text here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);

Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!

Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38
stealthcopter
  • 13,964
  • 13
  • 65
  • 83
5

Alternative solution: Using a WebView instead. Html is easy to work with.

WebView webview = new WebView(this);

String summary = "<html><body>Sorry, <span style=\"background: red;\">Madonna</span> gave no results</body></html>";

webview.loadData(summary, "text/html", "utf-8");
Vidar Vestnes
  • 42,644
  • 28
  • 86
  • 100
  • because of fromHTML() limitations, I'm heading for a tablet app with text in every panel displayed in a WebView. Welcome to the 2020s, where everything's a web page including your tablet's text view!~ – Phlip Apr 07 '21 at 22:04
5

font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")

NASSER
  • 5,900
  • 7
  • 38
  • 57
mhdtouban
  • 851
  • 2
  • 11
  • 20
5
 String name = modelOrderList.get(position).getName();   //get name from List
    String text = "<font color='#000000'>" + name + "</font>"; //set Black color of name
    /* check API version, according to version call method of Html class  */
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
        Log.d(TAG, "onBindViewHolder: if");
        holder.textViewName.setText(context.getString(R.string._5687982) + " ");
        holder.textViewName.append(Html.fromHtml(text));
    } else {
        Log.d(TAG, "onBindViewHolder: else");
        holder.textViewName.setText("123456" + " ");   //set text 
        holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY));   //append text into textView
    }
Khyati Vara
  • 1,042
  • 13
  • 22
1

To make part of your text underlined and colored

in your strings.xml

<string name="text_with_colored_underline">put the text here and &lt;u>&lt;font color="#your_hexa_color">the underlined colored part here&lt;font>&lt;u></string>

then in the activity

yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));

and for clickable links:

<string name="text_with_link"><![CDATA[<p>text before link<a href=\"http://www.google.com\">title of link</a>.<p>]]></string>

and in your activity:

yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
bsma
  • 88
  • 1
  • 10
1

First Convert your string into HTML then convert it into spannable. do as suggest the following codes.

 Spannable spannable = new SpannableString(Html.fromHtml(labelText));
                    
spannable.setSpan(new ForegroundColorSpan(Color.parseColor(color)), spannable.toString().indexOf("•"), spannable.toString().lastIndexOf("•") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            
Shashank Pandey
  • 683
  • 6
  • 14
0
textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));

It will give the color exactly what you have made in html editor , just set the textview and concat it with the textview value. Android does not support span color, change it to font color in editor and you are all set to go.

bummi
  • 27,123
  • 14
  • 62
  • 101
Naina
  • 49
  • 5
0

Adding also Kotlin version with:

  • getting text from resources (strings.xml)
  • getting color from resources (colors.xml)
  • "fetching HEX" moved as extension
fun getMulticolorSpanned(): Spanned {
    // Get text from resources
    val text: String = getString(R.string.your_text_from_resources)

    // Get color from resources and parse it to HEX (RGB) value
    val warningHexColor = getHexFromColors(R.color.your_error_color)

    // Use above string & color in HTML
    val html = "<string>$text<span style=\"color:#$warningHexColor;\">*</span></string>"

    // Parse HTML (base on API version)
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
    } else {
        Html.fromHtml(html)
    }
}

And Kotlin extension (with removing alpha):

fun Context.getHexFromColors(
    colorRes: Int
): String {
    val labelColor: Int = ContextCompat.getColor(this, colorRes)
    return String.format("%X", labelColor).substring(2)
}

Demo

demo

Boken
  • 4,825
  • 10
  • 32
  • 42