android项目开发中会遇到textView部分文字颜色不一,类似于,想要实现这种效果可以使用两个textView拼接,那如果有更多的不同颜色呢,总不能全部使用控件拼接吧。这里我们只需一个textView就可以实现,下面介绍我实现的两种方案:
方案一:主要使用的是Html.fromHtml方法实现的
StringBuilder stringBuilder=new StringBuilder(); stringBuilder.append("姓名:") .append("<font color=red>") .append("张三") .append("</font>"); tvResult.setText(Html.fromHtml(stringBuilder.toString()));
方案二:主要使用SpannableStringBuilder实现
String str = "姓名:张三"; SpannableStringBuilder builder = fillColor(str, "张三", Color.RED); tvResult.setText(builder == null ? str : builder);
private SpannableStringBuilder fillColor(String wholeStr, String highlightStr, int color) {
int start;
int end;
if (!TextUtils.isEmpty(wholeStr) && !TextUtils.isEmpty(highlightStr)) {
if (wholeStr.contains(highlightStr)) {
start = wholeStr.indexOf(highlightStr);
end = start + highlightStr.length();
} else {
return null;
}
} else {
return null;
}
SpannableStringBuilder spBuilder = new SpannableStringBuilder(wholeStr);
CharacterStyle charaStyle = new ForegroundColorSpan(color);
spBuilder.setSpan(charaStyle, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spBuilder;
}
如文字有多种颜色需要设置,则可:
SpannableStringBuilder spBuilder = new SpannableStringBuilder(wholeStr); ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED); ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(Color.BLUE); spBuilder.setSpan(colorSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spBuilder.setSpan(colorSpan1, 2, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
文字背景色则需使用 BackgroundColorSpan
BackgroundColorSpan colorSpan = new BackgroundColorSpan(Color.RED);