androidtextviewspannablestringspannablespannablestringbuilder

SpannableStringBuilder does not keep the style set in the text


I am trying to use SpannableStringBuilder to build a texts which that contains different styles. But the style is lost after appending more strings.

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;
}

The Textview displays the first two times "red" in Red colour and "green" in Green Colour the next times the style is lost and they are all the default colour in gray.

I have played with different options from the Spanned interface like SPAN_INCLUSIVE_EXCLUSIVE but it does not seem to work. enter image description here


Solution

  • try replace styleGreen in green.setSpan(styleGreen, 0, green.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); with new TextAppearanceSpan(getBaseContext(), R.style.Green)