Last Updated: February 25, 2016
·
3.851K
· chauvd

Highlighting Words in a String

While populating a ListView, I was hoping to highlight some keywords in the corresponding entries TextView. I had a Class for my data and a custom ArrayAdapter to flesh it out, but this can easily be modified to work on one input.

private Spannable highlightSearchKey(String title) {
    Spannable  highlight;
    Pattern    pattern;
    Matcher    matcher;
    int        word_index;
    String     title_str;

    word_index = words.length;
    title_str  = Html.fromHtml(title).toString();
    highlight  = (Spannable) Html.fromHtml(title);
    for (int index = 0; index < word_index; index++) {
        pattern = Pattern.compile("(?i)" + words[index]);
        matcher = pattern.matcher(title_str);
        while (matcher.find()) {
            highlight.setSpan(
                new BackgroundColorSpan(0x44444444), 
                matcher.start(), 
                matcher.end(), 
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return highlight;
}

The FOR loop iterates over each word in a keyword phrase, creates a regular expression pattern (which is case insensitive) and a corresponding matcher to grab each match in the main string ('title'). The WHILE loop uses the setSpan function to create a background box at each 'start' and 'end' index of a keyword. Once complete the returned Spannable can be used by a TextView directly.