这是一个工具类,很好用:
public class StringFormatUtil {
private SpannableStringBuilder spBuilder;
private String wholeStr, highlightStr;
private Context mContext;
private int color;
private int start = 0, end = 0;
/**
*
* @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;
}
public StringFormatUtil fillColor(){
if(!TextUtils.isEmpty(wholeStr)&&!TextUtils.isEmpty(highlightStr)){
if(wholeStr.contains(highlightStr)){
/*
* 返回highlightStr字符串wholeStr字符串中第一次出现处的索引。
*/
start=wholeStr.indexOf(highlightStr);