具有控制字符的可跨越字符串

时间:2014-08-01 13:57:48

标签: android textview

我想在TextView中显示不同颜色的文字,并将控制字符设置为断行\n和标签\t\t ...

我这样做......

SpannableStringBuilder   sb = new SpannableStringBuilder("");
ForegroundColorSpan fcs_red = new ForegroundColorSpan(Color.RED); 
ForegroundColorSpan fcs_blu = new ForegroundColorSpan(Color.BLUE); 

...
for(int j = 0; j < columns.length; j++)
{
    if(columns[j].equals("<")) continue;

    if(columns[j].contains("/") && columns[j].contains(":"))
    {
        columns[j] = columns[j].replace("<TD>", "\n");
        sb_aux = new SpannableStringBuilder(columns[j]);
        sb_aux.setSpan(fcs_red, 0, sb_aux.length(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }
    else
    {
        if(columns[j].contains("<TD>"))
        {
            columns[j] = columns[j].replace("<TD>", "\n\t\t");
            sb_aux = new SpannableStringBuilder(columns[j]);
            sb_aux.setSpan(fcs_blu, 0, sb_aux.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        }
        else
        {
            columns[j] = "\n\t\t"+columns[j];
            sb_aux = new SpannableStringBuilder(columns[j]);
            sb_aux.setSpan(fcs_blu, 0, sb_aux.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        }
    }
    sb.append(sb_aux);
}
myTextView.setText(sb);

因此,文本的第一部分按预期显示为红色,但其余文本未按预期交替显示为红色或蓝色,\n\t未被识别

我的目的是将文字分成几部分并附加到SpannableStringBuilderTextView显示,任何线索?

1 个答案:

答案 0 :(得分:0)

抱歉,我不了解您的密码,但这很简单:

String html = "<font color='red'>This is red</font>" +
              "<br/>Im in a new line\tdo some indent<b>BOLD</b>";

myTextView.setText(Html.fromHtml(html)); 
相关问题