Reputation: 2642
Heyo, I'm using SpannableStringBuilder
to change a word's each character color. This is how I use it :
SpannableStringBuilder specialSpan = new SpannableStringBuilder();
specialSpan.append(context.getResources().getString(R.string.asdf));
specialSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.blue)), 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
specialSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.purple)), 1, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
specialSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.orange)), 2, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
specialSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.green)), 3, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
userSpecialText.setText(specialSpan);
The problem is, the TextView
's color doesn't change. Am I missing something here?
Update :
I'm using this other Spannable string builder which works for adding Emojis
for (String part :
partofContent){
if (part.contains(":")){
int firstEq = sb.length();
Typeface font = FontCache.getTypeface("emojione-android.ttf", context);
String convertPart = Emojione.shortnameToUnicode(part, true);
sb.append(convertPart + " ");
int lastEq = sb.length();
sb.setSpan(new CustomTypefaceSpan("", font), firstEq, lastEq, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
sb.append(part + " ");
}
}
And to change the color of a detected user Alias
int aliasStart = sb.length();
sb.append("@" + alias + " ");
int aliasEnd = sb.length();
sb.setSpan(new MyClickableSpan("@" + alias + " "), aliasStart, aliasEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.miBlue)), aliasStart, aliasEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), aliasStart, aliasEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
That worked well too, and it uses the same ForegroundColorSpan
in setSpan()
.
Upvotes: 0
Views: 3511
Reputation: 4328
Try like This
SpannableStringBuilder specialSpan = new SpannableStringBuilder();
specialSpan.append(context.getResources().getString(R.string.asdf));
specialSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.blue)), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
specialSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.purple)), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
specialSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.orange)), 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
specialSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.green)), 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
userSpecialText.setText(specialSpan);
You're specifing same for both start and end that means you're specifying a span of length 0, not a span of length 1.
Upvotes: 1