Android – Highlight a Word In a TextView?

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

like

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

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

//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);
textView.setText(WordtoSpan);

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.

source: https://stackoverflow.com/a/10279703/2160827

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

usage:

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

Leave a Comment