4

我有三个正则表达式:

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

我有一个字符串:

这是@tom_cruise 的#sample #twitter 文本,带有链接http://tom_cruise.me

我需要将此文本与上述三个正则表达式匹配,并用蓝色为匹配的文本着色,并将最终文本设置为TextView. 我怎样才能做到这一点?

值得一提的是,我不需要Linkify文字,只需要着色。而且我没有使用Twitter4j图书馆。

4

2 回答 2

7

我替换http://tom_cruise.mehttp://www.google.com. 尝试以下操作:

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()));
于 2013-07-25T04:56:29.323 回答
0

看看SpannableStringSpannableStringBuilderhttps://stackoverflow.com/a/16061128/1321873SpannableStringBuilder提供了一个使用示例

您可以编写一个接受非样式String并返回CharSequence类似的方法:

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

然后使用上面的返回值来设置文本TextView

TextView tView = (TextView)findViewById(R.id.myText);
tView.setText(getStyledTweet(tweet));
于 2013-07-25T04:55:19.437 回答