2016-05-13 22 views
0

Heyo,我正在使用SpannableStringBuilder更改單詞的每個字符顏色。這是我如何使用它:Android - 使用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); 

這工作並且它在setSpan()中使用相同的ForegroundColorSpan

回答

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

你specifing相同的開始和結束,這意味着你指定長度爲0的跨度,而不是長度爲1

enter image description here

跨度
+0

我做到了這一點,我恢復了它..顏色仍然沒有改變.. –

+0

我已經嘗試過,而不是回答它,它是完美的工作。 –

+0

@ Kevin Murvie:嘗試更改標誌 - >> Spannable.SPAN_EXCLUSIVE_EXCLUSIVE爲「0」(零) –