public class StringFormatUtil {
private SpannableStringBuilder spBuilder;
private String wholeStr, highlightStr;
private Context mContext;
private int color;
/**
* @param context 上下文
* @param wholeStr 全部文字
* @param highlightStr 改变颜色的文字
* @param color 颜色
*/
public StringFormatUtil(Context context, String wholeStr, String highlightStr,
int color) {
this.mContext = context;
this.wholeStr = wholeStr;
this.highlightStr = highlightStr;
this.color = color;
}
/**
* 填充颜色
*
* @return StringFormatUtil
*/
public StringFormatUtil
fillColor() {
if (!TextUtils.isEmpty(wholeStr) && !TextUtils.isEmpty(highlightStr)) {
spBuilder =
new SpannableStringBuilder(wholeStr);
Pattern p = Pattern.compile(highlightStr);
Matcher m = p.matcher(spBuilder);
color = mContext.getResources().getColor(color);
while (m.find()) {
int start = m.start();
int end = m.end();
spBuilder.setSpan(
new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return this;
}
return null;
}
/**
* 获取到已经更改好的结果(这个时候已经实现了高亮,在获取这个result的时候不要toString()要不然会把色调去除的)
*
* @return result
*/
public SpannableStringBuilder
getResult() {
if (spBuilder !=
null) {
return spBuilder;
}
return null;
}
使用
new StringFormatUtil(holder
.itemView.getContext(), dataBean
.getTitle(), mLightStr, R
.color.colorAccent)
.fillColor()