3

I want to define different colors in single TextView like below:

<font color="yellow">Hi </font><font color="red">everybody</font>  

I saw this link: Is it possible to have multiple styles inside a TextView?. But it doesn't suit me. I would like to know how can I define it via XML. Is it possible to do this? Thanks

Community
  • 1
  • 1
Nolesh
  • 6,848
  • 12
  • 75
  • 112
  • Sorry we can do only in source code. Would be curious if we can do in xml. Can you tell why can't u use it by source code? – san Jan 09 '12 at 05:59

1 Answers1

3

we can't set in XML file but we can set as coding... You have to use text spannable.. here is example..

String text = "Hi @@hello@@";

TextView.setText(setSpanBetweenTokens(text, "@@", new ForegroundColorSpan(Color.RED)));

your setSpanBetweenTokens Method

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();
            int start = text.toString().indexOf(token) + tokenLen;
            int end = text.toString().indexOf(token, start);
        

if (start > -1 && end > -1)
      {               
          SpannableStringBuilder ssb = new SpannableStringBuilder(text);
          for (CharacterStyle c : cs)
              ssb.setSpan(c, start, end, 0);

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

          text = ssb;
      }
      return text;
  }
Community
  • 1
  • 1
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133