2011年11月21日 ⁄ Andriod百事查 ⁄ 暂无评论 ⁄ 被围观 25 views+      

 

/**

* 将text中@某人、#某主题、http://网址的字体加亮

* @param text

* @param context

* @return

*/

public static SpannableString formatContent(CharSequence text,Context context) {

SpannableString spannableString = new SpannableString(text);

/*

* @[^\\s::]+[::\\s] 匹配@某人            \\[[^0-9]{1,4}\\] 匹配表情

* #([^\\#|.]+)#       匹配#某主题       http://t\\.cn/\\w+ 匹配网址

*/

Pattern pattern = Pattern.compile("@[^\\s::]+[::\\s]|#([^\\#|.]+)#|http://t\\.cn/\\w+|\\[[^0-9]{1,4}\\]");

Matcher matcher = pattern.matcher(spannableString);

while (matcher.find()) {

String match=matcher.group();

if(match.startsWith("@")){ //@某人,加亮字体

spannableString.setSpan(new ForegroundColorSpan(0xff0077ff),

matcher.start(), matcher.end(),

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

}

else if(match.startsWith("#")){ //#某主题

spannableString.setSpan(new ForegroundColorSpan(0xff0077ff),

matcher.start(), matcher.end(),

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

}

else if(match.startsWith("http://")){ // 匹配网址

spannableString.setSpan(new ForegroundColorSpan(0xff0077ff),

matcher.start(), matcher.end(),

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

}

}

return spannableString;

}