如何在android中使用Regex为文本着色
我有三个正则表达式:
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
库。
我用http://www.google.com
替换了http://tom_cruise.me
。 请尝试以下方法:
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, "" + o.group(1) + ""); } o.appendTail(sb); Matcher n = mentionPattern.matcher(sb.toString()); sb = new StringBuffer(sb.length()); while (n.find()) { n.appendReplacement(sb, "" + n.group(1) + ""); } n.appendTail(sb); Matcher m = urlPattern.matcher(sb.toString()); sb = new StringBuffer(sb.length()); while (m.find()) { m.appendReplacement(sb, "" + m.group(1) + ""); } m.appendTail(sb); textView.setText(Html.fromHtml(sb.toString()));
看看SpannableString
和SpannableStringBuilder
。 有关使用SpannableStringBuilder
的示例,请访问https://stackoverflow.com/a/16061128/1321873
您可以编写一个接受非样式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));