Highlighting Text Color using Html.fromHtml() in Android?

AndroidTextHighlightTextview

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

Solution 3 - Android

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!

Solution 4 - Android

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");

Solution 5 - Android

 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
    }

Solution 6 - Android

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

Solution 7 - Android

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());

Solution 8 - Android

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.

Solution 9 - Android

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

Solution 10 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsunilView Question on Stackoverflow
Solution 1 - AndroidChristopher OrrView Answer on Stackoverflow
Solution 2 - AndroidSergeyAView Answer on Stackoverflow
Solution 3 - AndroidstealthcopterView Answer on Stackoverflow
Solution 4 - AndroidVidar VestnesView Answer on Stackoverflow
Solution 5 - AndroidKhyati VaraView Answer on Stackoverflow
Solution 6 - AndroidmhdtoubanView Answer on Stackoverflow
Solution 7 - AndroidbsmaView Answer on Stackoverflow
Solution 8 - AndroidNainaView Answer on Stackoverflow
Solution 9 - AndroidMuhammad Khurram MushtaqView Answer on Stackoverflow
Solution 10 - AndroidBokenView Answer on Stackoverflow