Android中TextView中的文字设置为不同颜色

时间:2023-03-09 00:42:26
Android中TextView中的文字设置为不同颜色
questionDesTextView=(TextView)findViewById(R.id.question_des);
SpannableStringBuilder builder = new SpannableStringBuilder(questionDesTextView.getText().toString());
//ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色
ForegroundColorSpan blackSpan = new ForegroundColorSpan(Color.BLACK);
ForegroundColorSpan graySpan=new ForegroundColorSpan(Color.GRAY);

//第二个参数是开始的下标,第三个参数是结束的下标
builder.setSpan(blackSpan, 0,4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(graySpan,4,9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
questionDesTextView.setText(builder);