一起学android之怎样设置TextView中不同字段的字体颜色(22)

在这里先看看效果图:



OK,有时候,在我们的项目中会要求TextView中文本有一部分的字体颜色不一样。这时我们应该使用


SpannableStringBuilder这个工具类,当然这个类的功能非常强大,这里我仅仅是实现上面的样式。其他的不做介绍。


SpannableStringBuilder的实现接口是Spannable这个接口,而Spannable终于都实现了CharSequence,因此我们直


接能够通过TextView.setText()来进行设置。


以下给出实现代码:

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;
	}
}

当然上面的第一步是获取你要改变颜色的文字的起始位置到结束位置,接着通过SpannableStringBuilder来改变文字

的颜色。


public class MainActivity extends Activity {
	private TextView tv_show;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		tv_show = (TextView) findViewById(R.id.tv_show);
		String wholeStr = "想要改变后面的颜色这是要改变的颜色";
		StringFormatUtil spanStr = new StringFormatUtil(this, wholeStr,
				"这是要改变的颜色", R.color.blue).fillColor();
		tv_show.setText(spanStr.getResult());
	}

}



转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/44225955 情绪控_

原文地址:https://www.cnblogs.com/yangykaifa/p/7229849.html