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

时间:2017-01-24 19:38:42

标签: android textview spannablestring spannable spannablestringbuilder

我正在尝试使用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显示前两次红色为“红色”,绿色为“绿色”,下一次失去样式,它们都是灰色的默认颜色。

我使用了跨越界面的不同选项,如SPAN_INCLUSIVE_EXCLUSIVE,但它似乎不起作用。 enter image description here

1 个答案:

答案 0 :(得分:1)

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