android TextView 设置部分文字背景色和文字颜色

时间:2014-09-19 19:24:56   收藏:0   阅读:279

通过SpannableStringBuilder来实现,它就像html里边的<span>元素改变指定文字的文字颜色或背景色

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		String str="这是设置TextView部分文字背景颜色和前景颜色的demo!";
		int bstart=str.indexOf("背景");
		int bend=bstart+"背景".length();
		int fstart=str.indexOf("前景");
		int fend=fstart+"前景".length();
		SpannableStringBuilder style=new SpannableStringBuilder(str); 
		style.setSpan(new BackgroundColorSpan(Color.RED),bstart,bend,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);   
        style.setSpan(new ForegroundColorSpan(Color.RED),fstart,fend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); 
		TextView tvColor=(TextView) findViewById(R.id.tv_color);
		tvColor.setText(style);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

bubuko.com,布布扣

原文:http://blog.csdn.net/shaohx0518/article/details/39401385

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!