2017-02-07 12 views
0

AndroidでTextViewのすべてを表示するロガーを作成する必要があるというケースを想像してみましょう。TextViewにHTMLコンテンツを追加する

私は複数行のTextViewを作成します。ログには、いくつかの悪い情報(例えばHTTP 500)を返すとき

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

魔法のように動作しますが、私は赤色のテキスト(またはテキストの背景)を追加したい:その後、当初のTextViewに単純なテキストを追加するための方法を持っています。だから私は、メソッドを更新し、いくつかの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

[OK]を、ので、いくつかのより深く検索した後、私は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; 
} 

をそして、それはトリックをした

関連する問題