开发中会遇到一种情况,TextView设置文本时,其中一些字体颜色要区分其他文本颜色。例如“我爱中国,我是中华儿女我骄傲!”,要求中国两字颜色为红色。这个时候可以使用下方这个方法。
public static SpannableString getHighLightKeyWord(int color, String text, String keyword) {
SpannableString str = new SpannableString(text);
Pattern pattern = Pattern.compile(keyword);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
str.setSpan(new ForegroundColorSpan(color), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return str;
}



