Reputation: 7018
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
Upvotes: 3
Views: 3232
Reputation: 33238
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; }
Upvotes: 3