我对SpannableString对象有问题。

下面是一个简短的示例:

SpannableString spanstr = new SpannableString("Bold please!");
spanstr.setSpan(new StyleSpan(Typeface.BOLD), 0, spanstr.length(), 0);

SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(spanstr);
sb.append("\n"); // A newline
sb.append("The first line is bold. This one isn't.");

CharSequence cq = sb.subSequence(0, sb.length());
// ^There's no such method to return a SpannableString,
// so I try to return a CharSequence instead.

// And then, at last:
TextView contentView = (TextView) findViewById(R.id.some_id);
contentView.setText(cq);

该示例试图做的是显示以下内容:



但是问题是:文本的第一行不会以粗体显示。

为什么不如预期的那样?

最佳答案

使用可跨度的字符串构建器将其设置为textview中的文本:

contentView.setText(sb);

否则你可以这样:
SpannableStringBuilder spanstr = new SpannableStringBuilder("Bold please!");
spanstr.setSpan(new StyleSpan(Typeface.BOLD), 0, spanstr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanstr.append("\n");
spanstr.append("The first line is bold. This one isn't.");
contentView.setText(spanstr);

10-08 18:27