是否可以使用 if 条件为 TextView 内的不同文本设置多种颜色?
这是我的代码:
mColoredText = findViewById(R.id.questionText);
String mColoredString = "BLACK RED GREEN YELLOW ORANGE BLUE WHITE";
SpannableStringBuilder builder = new SpannableStringBuilder();
if(mColoredString.contains("RED")) {
String red = "RED";
SpannableString redSpannable = new SpannableString(red);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
builder.append(redSpannable);
}
if(mColoredString.contains("YELLOW")) {
String yellow = "YELLOW";
SpannableString whiteSpannable = new SpannableString(yellow);
whiteSpannable.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, yellow.length(), 0);
builder.append(whiteSpannable);
}
if(mColoredString.contains("BLUE")) {
String blue = "BLUE";
SpannableString blueSpannable = new SpannableString(blue);
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(), 0);
builder.append(blueSpannable);
}
mColoredText.setText(builder, TextView.BufferType.SPANNABLE);
但最终的结果总是打印:RED YELLOW BLUE 和它的颜色,只有三个文本。
我希望 BLACK RED GREEN YELLOW ORANGE BLUE WHITE 写在一起,如果没有可扩展的颜色,则适用白色。