android-修改TextView中部分文字的颜色

 

[java]  view plain copy
  1. textView = (TextView) findViewById(R.id.textview);  
  2. SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());  
  3.   
  4. //ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色  
  5. ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);  
  6. ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);  
  7. ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);  
  8. ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN);  
  9. ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW);  
  10.   
  11.   
  12.   
  13. builder.setSpan(redSpan, 01, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  14. builder.setSpan(whiteSpan, 12, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  15. builder.setSpan(blueSpan, 23, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  16. builder.setSpan(greenSpan, 34, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  17. builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  18.   
  19. textView.setText(builder);  

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,这是在 setSpan 时需要指定的 flag,它的意义我试了很久也没试出来,睡个觉,今天早上才突然有点想法,试之,果然。它是用来标识在 Span 范围内的文本前后输入新的字符时是否把它们也应用这个效果。分别有 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括,后面不包括)、Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括,后面包括)、Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)。看个截图就更明白了: 


 
对比一下 

 


测试的Demo

public void setTextColor3() {
		mTextView = (TextView) findViewById(R.id.textview);

		// ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色
		//ForegroundColorSpan不能被复用,属于一次性属性,只能给一个字段赋这样的属性
		ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
		ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);
		ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);
		ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN);
		ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW);

		String[] array = { "word", "tell", "me", "hhe", "wo", "heihei","shuia", "ui" };
		int[] score = { 90, 59, 90, 12, 22, 61, 11, 79 };

		SpannableStringBuilder builder1 = new SpannableStringBuilder("");
		int start = 0;
		int end = 0;
		for (int i = 0; i < array.length; i++) {
			
			start = builder1.length();
			builder1.append(array[i] + " ");//添加你的字符串
			end = builder1.length();
			
			if (score[i] > 60) {
				builder1.setSpan(new ForegroundColorSpan(Color.GREEN), start,
						end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			} else {
				builder1.setSpan(new ForegroundColorSpan(Color.RED), start,
						end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			}

		}
		mTextView.setText(builder1);

	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值