用到过很多次,每次在用的时候,思路就会断线,以此特意写出来,帮助自己记忆;
修改TextView 中部分文字的颜色
- textView = (TextView) findViewById(R.id.textview);
- SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());
- //ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色
- 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);
二、外部方法调用
private TextView tv_samplenumber_lan;
tv_samplenumber_lan=(TextView) findViewById(R.id.tv_samplenumber_lan);
tv_samplenumber_lan=dofor(tv_samplenumber_lan);
public static TextView dofor(TextView str){ SpannableStringBuilder builder = new SpannableStringBuilder(str.getText().toString()); //ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色 ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED); if (str.getText().toString().substring(4,5).equals("*")){ builder.setSpan(redSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); }else if (str.getText().toString().substring(7,8).equals("*")){ builder.setSpan(redSpan, 7,8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } str.setText(builder); return str; }特意附上大神给讲解的实例代码