簡體   English   中英

Spansables不為TextView中的文本着色

[英]Spannables not coloring text in TextView

我正在嘗試給單詞的最后兩個字母加上顏色,但是當我應用跨度時,什么也沒發生。

這是應用跨度的代碼:

oldWordTextView.setHighlightStatus(true);
    //Span koji uzima cijeli tekst
    String word = oldWordTextView.getText().toString();
    Log.w(word, "Rijec za animiranje highlight");
    Log.w("U animiranju prefixa", "Aniamte");
    if(word != "" && word != " "){
    final SpannableStringBuilder oldSb = new SpannableStringBuilder(word);
    final SpannableStringBuilder currentSb = new SpannableStringBuilder(buffer);

    //Span za mijenjanje boje
    final ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.rgb(60, 184, 120));//Green
    final ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.rgb(251, 43, 51));//Red
    Spannable wordToSpan = new SpannableString(word);

    if(isValid){
        wordToSpan.setSpan(greenSpan, word.length() - 2, word.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        oldSb.setSpan(greenSpan, word.length() - 2, word.length() - 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        if(buffer != "" && buffer != " ") currentSb.setSpan(greenSpan, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        oldWordTextView.setText(wordToSpan, BufferType.SPANNABLE);
        //staticTextView.setText(currentSb);
        isHighlightDone = true;
    }
    else{
        oldSb.setSpan(redSpan, 0, word.length() - 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        if(buffer != "" && buffer != " ") currentSb.setSpan(redSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        oldWordTextView.setText(oldSb);
        staticTextView.setText(currentSb);
    }
    }

這是自定義后的TextView類: http : //pastebin.com/4qxL3m82

謝謝!

編輯:我已經測試並推斷出問題出在我的自定義textview類中。 我曾嘗試在onDraw和onLayout方法中應用跨度,但是textView保持不變。 有任何想法嗎?

最簡單的方法是在字符串中包含HTML:

String str = "This word is <font color='#EE0000'>red</font>";
t.setText(Html.fromHtml(str));

為了顯示SpannableString,您還需要傳遞如下標志:

textView.setText(spannableString, TextView.BufferType.SPANNABLE);

我個人更喜歡創建實用程序函數以給定String的某些部分着色。 例如,假設您想要一個功能來突出顯示一個字符並用另一種顏色給其他字符着色。 您可以實現以下內容:

// this function colors the k-th character of String s in blue and the rest in red, and returns the SpannableString
public static SpannableString highlight(String s, int k) {
        SpannableString ss = new SpannableString(s);
        ss.setSpan(new ForegroundColorSpan(Color.BLUE), 0, k, 0);
        ss.setSpan(new ForegroundColorSpan(Color.RED), k, k + 1, 0);
        ss.setSpan(new ForegroundColorSpan(Color.BLUE), k + 1, s.length(), 0);
        return ss;
    }

編輯 :好吧,我看到問題是您的方法applyLetterSpacing只是忽略了舊的范圍。 因此,我想到的第一個解決方案是在調用setText時保存跨度,並在調用applyLetterSpacing時應用applyLetterSpacing 您可以在http://pastebin.com/p4Hig8Pj中看到該想法,盡管正如我在評論中所說,在onDrawonLayout使用自定義着色器會使着色效果完全出乎意料。 希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM