让TextView中有一部分变色很多种方法:
1.
textview.setText(Html.fromHtml(“后面文字颜色属性不一样:变色文字“));
2.
String wholeStr = “后面的颜色将要改变哈哈哈这是要改变的颜色”;
StringFormatUtil spanStr = new StringFormatUtil(this, wholeStr, “这是要改变的颜色”, R.color.blue).fillColor();
textview.setText(spanStr.getResult());
需要用到StringFormatUtil类:
源码:
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);
end=start+highlightStr.length();
}else{
return null;
}
}else{
return null;
}
spBuilder=new SpannableStringBuilder(wholeStr);
color=mContext.getResources().getColor(color);
CharacterStyle charaStyle=new ForegroundColorSpan(color);
spBuilder.setSpan(charaStyle, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return this;
}
public SpannableStringBuilder getResult(){
if (spBuilder != null) {
return spBuilder;
}
return null;
}
}
自定义变色(也可点击变色)View: