2

I want to highlight a particular word in a text view ( more specifically similar to a twitter feed). The word may occur multiple times. Below I will post a sample sentence from twitter.

" Mumbai Master Blaster! #Sachin. Greatest players of all times. The legend of cricket #sachin. "

Here I want to highlight the word " #Sachin " with a particular color. Also please note that we don't know how many times this word could get repeated in the whole string. Could anyone help me to solve this issue.

Mohit
  • 2,940
  • 2
  • 24
  • 32
Sanal Varghese
  • 1,465
  • 4
  • 23
  • 46

1 Answers1

0

Use next code:

public CharSequence linkifyHashtags(String text) {
    SpannableStringBuilder linkifiedText = new SpannableStringBuilder(text);
    Pattern pattern = Pattern.compile("@\\w");
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();
        String hashtag = text.substring(start, end);
        ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
        linkifiedText.setSpan(span, 0, hashtag.length(), 0);
    }
    return linkifiedText;
}
danik
  • 796
  • 9
  • 17