在Android中经常会需要在一段文字中使用不用的颜色,有以下两种办法:
1. 使用ForegroundColorSpan显示不同颜色
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
/**
* 设置TextView部分颜色变色
*
* @param textView 控件
* @param foregroundColorSpan 颜色
* @param starIndex 变色初始位置
* @param endIndex 变色结束位置
*/
public static void setTextForColor(TextView textView, ForegroundColorSpan foregroundColorSpan, int starIndex, int endIndex) {
SpannableStringBuilder style = new SpannableStringBuilder(textView.getText().toString());
style.setSpan(foregroundColorSpan, starIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(style);
}
缺点:若文字需要多个地方变色则需要重复调用。
2. 使用Html特性显示不同颜色
Android中除了使用ForegroundColorSpan以后,在一些场景下我们可以使用html的特性来给TextView的部分文字变色:
// 要替换字符串的正则
String REG = "(\\[(\\#[0-9a-fA-F]{6,8})\\])(((?!\\[\\#).)*)(\\[\\#[G]{6,8}\\])";
// 替换指定的字符串为html标签
String str = "我分享了装备[#CC33FF]轩辕剑[#GGGGGG],而且[#FF0000]这[#GGGGGG][#FF7F00]是[#GGGGGG][#FFFF00]七[#GGGGGG][#00FF00]彩[#GGGGGG][#00FFFF]的[#GGGGGG][#0000FF]颜[#GGGGGG][#8B00FF]色[#GGGGGG],你喜欢吗?70"
String html = str.replaceAll(REG, "<font color="$2">$3</font>");
// 显示到TextView上
String html = Html.fromHtml(s);
textView.setText(html);

3. 在TextView中插入图片:
// 在文字前后添加图标
private CharSequence addImageForBothSides(String str, int leftImageResId, int rightImageResId) {
StringBuilder builder = new StringBuilder();
if (leftImageResId > 0) {
builder.append("<img src=\"");
builder.append(leftImageResId);
builder.append("\"> ");
builder.append(" ");
}
builder.append(str);
if (rightImageResId > 0) {
builder.append(" ");
builder.append("<img src=\"");
builder.append(rightImageResId);
builder.append("\">");
}
return Html.fromHtml(builder.toString(), imageGetter, null);
}
/**
* 获取本地图片资源
*/
private Html.ImageGetter imageGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int id = Integer.parseInt(source);
// 根据id从资源文件中获取图片对象
BitmapDrawable d = (BitmapDrawable) Global.getAppContext().getResources().getDrawable(id);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight() + 10);
d.setGravity(Gravity.TOP);
return d;
}
};

网友评论