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

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.

This question is related to android text highlight textview

The answer is


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("Add all your funky text in 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!


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


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

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.


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

 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
    }

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

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

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


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to text

Difference between opening a file in binary vs text How do I center text vertically and horizontally in Flutter? How to `wget` a list of URLs in a text file? Convert txt to csv python script Reading local text file into a JavaScript array Python: How to increase/reduce the fontsize of x and y tick labels? How can I insert a line break into a <Text> component in React Native? How to split large text file in windows? Copy text from nano editor to shell Atom menu is missing. How do I re-enable

Examples related to highlight

Manually highlight selected text in Notepad++ jQuery "blinking highlight" effect on div? highlight the navigation menu for the current page Highlighting Text Color using Html.fromHtml() in Android? Changing the highlight color when selecting text in an HTML text input How to disable text selection highlighting Vim clear last search highlighting LaTeX package for syntax highlighting of code in various languages How do you make an element "flash" in jQuery How do you make Vim unhighlight what you searched for?

Examples related to textview

Kotlin: How to get and set a text to TextView in Android using Kotlin? How to set a ripple effect on textview or imageview on Android? The specified child already has a parent. You must call removeView() on the child's parent first (Android) Android: Creating a Circular TextView? android on Text Change Listener Android - Set text to TextView Placing a textview on top of imageview in android Rounded corner for textview in android Different font size of strings in the same TextView Auto-fit TextView for Android