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, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
14 builder.setSpan(whiteSpan, 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
15 builder.setSpan(blueSpan, 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
16 builder.setSpan(greenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
17 builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
18
19 textView.setText(builder);/**
* 设置SpannableString 样式
*设置相应位置文字颜色及样式
* @param s 传入的string
* @param start 开始位置
* @param end 结束位置
* @return SpannableString
*/
fun getSpannableString(s: String, start: Int, end: Int): SpannableString {
val spannableString = SpannableString(s)
val colorSpan_a = ForegroundColorSpan(Color.parseColor("#333333"))
val colorSpan_b = ForegroundColorSpan(Color.parseColor("#151515"))
val styleSpan = StyleSpan(Typeface.BOLD)
spannableString.setSpan(styleSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)//粗体
spannableString.setSpan(colorSpan_a, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)//黑色
spannableString.setSpan(colorSpan_b, end, spannableString.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)//描述色彩#151515
return spannableString
}