Why doesn't my text show up with style when using SpannableStringBuilder?

MC Emperor picture MC Emperor · Apr 17, 2013 · Viewed 9.1k times · Source

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?

Answer

Eldhose M Babu picture Eldhose M Babu · Apr 17, 2013

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