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

来源:互联网 发布:4g网络制式 编辑:程序博客网 时间:2024/04/30 13:57

 

[java] view plaincopy
  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);}





0 0
原创粉丝点击