如果您不反对使用 html:
tv.setText(Html.fromHtml(makeStringBuffer(text, regex, Color.RED).toString()));
private StringBuffer makeColoredStringBuffer(String text, String regex, int color) {
// create a buffer to hold the replaced string
StringBuffer sb = new StringBuffer();
// create the pattern matcher
Matcher m = Pattern.compile(regex).matcher(text);
// iterate through all matches
while (m.find()) {
// get the match
String word = m.group();
// remove the first and last characters of the match and surround with html font tag
String abbr = String.format("<font color='#%06X'>%s</font>", (0xFFFFFF & color), word.substring(1, word.length() - 1));
// appendReplacement handles replacing within the current match's bounds
m.appendReplacement(sb, abbr);
}
// add any text left over after the final match
m.appendTail(sb);
return sb;
}
如果你想使用一个SpannableString
:
tv.setText(makeColoredSpannable(text, regex, Color.RED));
private SpannableStringBuilder makeColoredSpannable(String text, String regex, int color) {
// create a spannable to hold the final result
SpannableStringBuilder spannable = new SpannableStringBuilder();
// create a buffer to hold the replaced string
StringBuffer sb = new StringBuffer();
// create the pattern matcher
Matcher m = Pattern.compile(regex).matcher(text);
// iterate through all matches
while (m.find()) {
// get the match
String word = m.group();
// remove the first and last characters of the match
String abbr = word.substring(1, word.length() - 1);
// clear the string buffer
sb.setLength(0);
// appendReplacement handles replacing within the current match's bounds
m.appendReplacement(sb, abbr);
// append the new colored section to the spannable
spannable.append(sb);
spannable.setSpan(new ForegroundColorSpan(color), spannable.length() - abbr.length(), spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
// clear the string buffer
sb.setLength(0);
// add any text left over after the final match
m.appendTail(sb);
spannable.append(sb);
return spannable;
}