2017-02-07 40 views
0

讓我們想象一個用例,我需要在Android上創建一個記錄器,並在TextView中顯示所有內容。在TextView中附加HTML內容

所以我創建了一個多行TextView。然後開始有添加簡單的文本TextView的方法:

TextView output; // Initialized in onCreate 
public static void log(final String text) { // Method is called always when Log.log is called 
    output.append(text + "\n"); 
} 

這就像一個魅力,但我想添加紅色文本(或文本背景)當日志返回一些不好的信息(例如HTTP 500) 。所以,我已經更新的方法和使用的一些HTML:

public static void log(final String text) { 
    String newText = output.getText().toString(); 
    if (text.contains("500")) { 
    newText += "<font color='#FF0000'><b>" + text + "</b></font><br />"; 
    } else { 
    newText += text + "<br />"; 
    } 
    output.setText(Html.fromHtml(newText), TextView.BufferType.SPANNABLE); 
} 

但它始終格式只是當前的「文本」,一切都在那之前(output.getText())未格式化。似乎TextView不保留帶有HTML標籤的文本,只是一次裝飾。

我想是這樣的:

spannableString.setSpan(new BackgroundColorSpan(color), 0, 
        text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

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

哪做的彩色背景,但只是當前文本。我希望有像白線這樣的輸出,並且當大約500時顯示一些紅線(所以它是動態的)。

任何想法?

回答

1

好了,經過一番越深的搜索,我發現SpannableStringBuilder,我改變了代碼:

public static void log(final String text) { 
    // Could be instantiate just once e.g. in onCreate and here just appending 
    SpannableStringBuilder ssb = new SpannableStringBuilder(output.getText()); 
    if (text.contains("500")) { 
    ssb.append(coloredText(text + "\n", Color.parseColor("red"))); 
    } else { 
    ssb.append(text).append("\n"); 
    } 
    output.setText(ssb, TextView.BufferType.SPANNABLE); 
} 


private static SpannableString coloredText(String text, int color) { 
    final SpannableString spannableString = new SpannableString(text); 
    try { 
    spannableString.setSpan(new BackgroundColorSpan(color), 0, 
        text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    } catch (Exception e) {} 
    return spannableString; 
} 

這奏效了