为什么我的文字显示风格使用SpannableStringBuilder什么时候?我的、什么时候、风格、文字

2023-09-04 12:33:31 作者:沉默╮敷衍的烂借口

我有一个 SpannableString 对象的一个​​问题。

I have a problem with a SpannableString object.

下面是一个简单的例子:

Below's a short example:

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

什么例子正试图做的是显示出这一点:

What the example's trying to do is showing this:

粗体请!   第一行是大胆的。这一个不是。

Bold please! The first line is bold. This one isn't.

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

But the problem is: the first line of the text won't show up in bold.

为什么它不这么做预期?

Why doesn't it do it expected?

推荐答案

使用的spannable字符串生成器在TextView中设置为文本:

Use the spannable string builder for setting as text in textview :

contentView.setText(sb);

否则,你可以这样做:

or else you can do like this :

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