Alternate coloring of each character of a string with setSpan() not coloring correctly Android?

StackOverflow https://stackoverflow.com/questions/20530379

  •  31-08-2022
  •  | 
  •  

Question

I'm trying to do an alternate coloring of each character of an input string using SpannableString's setSpan(), but somehow the outputted string is not colored properly.

//ColorLogic.java:
public SpannableString colorString(String myStr)
{
    SpannableString spnStr=new SpannableString(myStr);
    int strLen=myStr.length();
    for(int i=0; i< strLen; i++)
    {
        if (i%2==0)
        {
             Log.v(DTAG, "vow"+myStr.charAt(i));
             spnStr.setSpan(new ForegroundColorSpan(Color.RED), i, i, 0);

        }
        else
        {
            Log.v(DTAG, "cons"+myStr.charAt(i));
            spnStr.setSpan(new ForegroundColorSpan(Color.BLUE), i, i, 0);
        }
    }
    return spnStr;
}

//In my OnCreate of my activity class:
 // Create the text view
 TextView textView = new TextView(this);
 textView.setTextSize(50);

 //Call Color Logic to color each letter individually
 ColorLogic myColorTxt=new ColorLogic();
 SpannableString spnMsg=myColorTxt.colorString(message);
 textView.setText(spnMsg, BufferType.SPANNABLE);
 setContentView(textView);
 }

 output: 
  ![2 letters][1]
   [1]: http://i.stack.imgur.com/rA8TV.png
   ![3 letters][1]
    [1]: http://i.stack.imgur.com/X039z.png

I have noticed that if I simply have :

spnStr.setSpan(new ForegroundColorSpan(Color.RED), 0, 0, 0);

Then ALL the characters of the string is colored red, even though I had specified the start and stop to be the 1st char. I've tried different Spannable flags such as: android.text.Spannable.SPAN_INCLUSIVE_INCLUSIVE , but the same problem still occurs.

Was it helpful?

Solution

You're specifing i for both start and end - this means you're specifying a span of length 0, not a span of length 1. Try this:

spnStr.setSpan(new ForegroundColorSpan(Color.RED), i, i + 1, 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top