如何改变Textview的部分文字颜色

来源:互联网 发布:个人如何使用阿里云 编辑:程序博客网 时间:2024/05/20 09:46

              最近项目需求,一个textview中有好几种文字颜色,开始使用好几个textview拼接的,最近决定改进一下,特意记录一下,  以防下次使用忘记


textView = (TextView) findViewById(R.id.textview);  
SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());  
  
//要设置的文字颜色
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);  
  
  
  //按照位置给部分文字设置颜色
builder.setSpan(redSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
builder.setSpan(whiteSpan, 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
builder.setSpan(blueSpan, 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
builder.setSpan(greenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  
textView.setText(builder);  
 
  

ok啦!
 
阅读全文
0 0