• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps SpannableStringBuilder won't add more than 1 span?

sas41

Lurker
Hello,
I am trying to create a method to format my text so that I can have colored text in my TextView elements.

This is my method and how I call it:

http://pastebin.com/gP8Xx3KA

Java:
setSpanBetweenTokens("NORMAL, ##COLORED##, NORMAL, ##COLORED##", "##",  new ForegroundColorSpan(0xFFFF0000))

public static CharSequence setSpanBetweenTokens(CharSequence text, String token, CharacterStyle... cs)
{
    // Start and end refer to the points where the span will apply
    int tokenLen = token.length(); //2
    int start = text.toString().indexOf(token) + tokenLen; //Where the Token is + it's length = where the text  begins.
    int end = text.toString().indexOf(token, start); //Find the next token that comes after the last one.

    // Copy the spannable string to a mutable spannable string
    SpannableStringBuilder ssb = new SpannableStringBuilder(text);

    while (start > -1 && end > -1) {

        for (CharacterStyle c : cs) {

            ssb.setSpan(c, start, end,  33);

        }

        // Delete the tokens before and after the span
        ssb.delete(end, end + tokenLen);
        ssb.delete(start - tokenLen, start);

        start = ssb.toString().indexOf(token) + tokenLen;
        end = ssb.toString().indexOf(token, start);

    }

    return ssb;
}

Any ideas why it only returns with a single span instead of 2?
 
Last edited:
Back
Top Bottom