Android – Highlight a Word In a TextView?

insert HTML code for color around word and set it to your textView .


String newString = oldString.replaceAll(textToHighlight, "<font color="red">"+textToHighlight+"</font>");

TextView textView = (TextView)findViewById(;

//use a loop to change text color
Spannable WordtoSpan = new SpannableString("partial colored text");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

The numbers 2 and 4 are start/stop indexes for the coloring of the text, in this example “rti” would be colored.

So you would basically just find the starting index of your searching word in the title:

int startIndex = titleText.indexOf(term);
int stopIndex = startIndex + term.length();

and then replace the numbers 2 and 4 with the indexes and “partial colored text” with your title string.


I know it’s old question but i have created a method to highlight a repeated-word in stringparagraph.

private Spannable highlight(int color, Spannable original, String word) {
    String normalized = Normalizer.normalize(original, Normalizer.Form.NFD)
            .replaceAll("\p{InCombiningDiacriticalMarks}+", "");

    int start = normalized.indexOf(word);
    if (start < 0) {
        return original;
    } else {
        Spannable highlighted = new SpannableString(original);
        while (start >= 0) {
            int spanStart = Math.min(start, original.length());
            int spanEnd = Math.min(start+word.length(), original.length());

            highlighted.setSpan(new ForegroundColorSpan(color), spanStart,
                    spanEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            start = normalizedText.indexOf(word, spanEnd);
        return highlighted;


textView.setText(highlight(primaryColor, textAll, wordToHighlight));

Leave a Comment