SpannableStringBuilder 不保留文本中设置的样式

SpannableStringBuilder does not keep the style set in the text

我正在尝试使用 SpannableStringBuilder 构建包含不同样式的文本。但是添加更多字符串后样式丢失了。

public SpannableStringBuilder buildMixStyleText() {
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();

    TextAppearanceSpan styleRed = new TextAppearanceSpan(getBaseContext(), R.style.Red);
    TextAppearanceSpan styleGreen = new TextAppearanceSpan(getBaseContext(), R.style.Green);

    for (int i = 0; i < 10; i++) {
        SpannableString red = new SpannableString("red");
        red.setSpan(styleRed, 0, red.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.append(red);
        spannableStringBuilder.append("\n");

        SpannableString green = new SpannableString("green");
        green.setSpan(styleGreen, 0, green.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.append(green);
        spannableStringBuilder.append("\n");

    }
    return spannableStringBuilder;
}

Textview前两次显示"red"红色,"green"绿色,下一次样式丢失,都是默认的灰色。

我玩过 Spanned 界面中的不同选项,例如 SPAN_INCLUSIVE_EXCLUSIVE,但它似乎不起作用。

尝试替换 green.setSpan(styleGreen, 0, green.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) 中的 styleGreennew TextAppearanceSpan(getBaseContext(), R.style.Green)