Android - 使用SpannableStringBuilder进行每个字符的颜色更改

时间:2016-05-13 09:09:01

标签: android spannablestring

Heyo,我正在使用the appearance of each track is updated更改单词的每个字符颜色。这就是我使用它的方式:

SpannableStringBuilder

问题是,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); 的颜色不会改变。我在这里错过了什么吗?

更新:

我正在使用另一个可用于添加TextView

的Spannable字符串构建器
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 + " ");
    }
}

效果也很好,它在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); 中使用相同的ForegroundColorSpan

1 个答案:

答案 0 :(得分:0)

试试这个

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);

您为开始和结束指定相同意味着您指定的长度为0,而不是长度为1的跨度。

enter image description here