Kaidul
Kaidul

Reputation: 15885

How to color text using Regex in android

I have three regular expression:

Pattern mentionPattern = Pattern.compile("(@[A-Za-z0-9_-]+)");
Pattern hashtagPattern = Pattern.compile("(#[A-Za-z0-9_-]+)");
Pattern urlPattern = Patterns.WEB_URL;

I have a string :

This is a #sample #twitter text of @tom_cruise with a link http://tom_cruise.me

I need to match this text with the above three regular expression and color the matched text with Blue and set the final text in a TextView. How can I achieve that?

It is to be mentioned that I don't need to Linkify the text, only coloring. And I am not using Twitter4j Library.

Upvotes: 4

Views: 2470

Answers (2)

Vikram
Vikram

Reputation: 51571

I replaced http://tom_cruise.me with http://www.google.com. Try the following:

String a = "This is a #sample #twitter text of @tom_cruise with a link http://www.google.com";

Pattern mentionPattern = Pattern.compile("(@[A-Za-z0-9_-]+)");
Pattern hashtagPattern = Pattern.compile("(#[A-Za-z0-9_-]+)");
Pattern urlPattern = Patterns.WEB_URL;

StringBuffer sb = new StringBuffer(a.length());
Matcher o = hashtagPattern.matcher(a);

while (o.find()) {
    o.appendReplacement(sb, "<font color=\"#437C17\">" + o.group(1) + "</font>");
}
o.appendTail(sb);

Matcher n = mentionPattern.matcher(sb.toString());
sb = new StringBuffer(sb.length());

while (n.find()) {
    n.appendReplacement(sb, "<font color=\"#657383\">" + n.group(1) + "</font>");
}
n.appendTail(sb);

Matcher m = urlPattern.matcher(sb.toString());
sb = new StringBuffer(sb.length());

while (m.find()) {
    m.appendReplacement(sb, "<font color=\"#EDDA74\">" + m.group(1) + "</font>");
}
m.appendTail(sb);

textView.setText(Html.fromHtml(sb.toString()));

Upvotes: 7

Rajesh
Rajesh

Reputation: 15774

Take a look at SpannableString and SpannableStringBuilder. An example of using the SpannableStringBuilder is available at https://stackoverflow.com/a/16061128/1321873

You could write a method that accepts the non-styled String and returns a CharSequence like so:

private CharSequence getStyledTweet(String tweet){
    SpannableStringBuilder stringBuilder = new SpannableStringBuilder(tweet);
    //Find the indices of the hashtag pattern, mention pattern and url patterns 
    //and set the spans accordingly
    //...
    return stringBuilder;
}

and then use the return value from the above to set the text of the TextView

TextView tView = (TextView)findViewById(R.id.myText);
tView.setText(getStyledTweet(tweet));

Upvotes: 0

Related Questions