Find and Colorize Specific Words (Hashtags) in a String (TextView)

A user on Stack Overflow came up with an interesting problem to find and colorize specific words that are hashtags in a given string extracted from a TextView.

The solution is quite simple to achieve unless you’re new to Android development or Java programming.

The problem was that the user wanted to identify or match hashtags from a given text (in a TextView) and colorize every hashtag in it. Well, this has a very simple approach and can be achieved easily with a just a few lines of code.

Here’s the final output what the user wanted:

Find and Color Hashtag in TextView

Here’s the sample code which will obtain the string from the TextView, and using Java’s in-built java.util.regex.Pattern class, we can define a pattern that we would like to find in the string. With the help of Matcher class, we will find for the exact alphanumeric pattern that begin with the hash symbol.

When an appropriate match is found, we set the color of the particular pattern by passing the start and end index value.

<br />SpannableString hashText = new SpannableString(text.getText().toString());<br />Matcher matcher = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashText);<br />while (matcher.find()) {<br /><%%KEEPWHITESPACE%%>        hashText.setSpan(new ForegroundColorSpan(Color.BLUE), matcher.start(), matcher.end(), 0);<br />}<br />text.setText(hashText);<br />

Hope this helps to anyone else who is finding a way to do it.