Android SpannableString(Builder) does not apply style

1.1k views Asked by At
SpannableStringBuilder str = new SpannableStringBuilder(decimalFormat.format(prizes[0])
    + "€");
str.setSpan(new StyleSpan(BOLD), 0, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

money.setText("paid | " + str);

This code should produce the same result as this code

money.setText(Html.fromHtml("paid | <strong>" + decimalFormat.format(prizes[0]) 
    + "€</strong>")

But it does not! My text does not come out bold. The fromHtml() one does make it bold like this: This is how I want it to appear because over here they said that it is better in performance and I want to use native android funtions. Using SpannableStringBuilder it displays like this: With nothing bold. I also tried just using SpannableString instead of SpannableStringBuilder, but that didn't change anything either. What am I doing wrong?

My money variable is a TextView.

2

There are 2 answers

2
creativecreatorormaybenot On BEST ANSWER

I found the answer myself. I was sure that I tried that before, but it works like this: textView.setText(spannableStringBuilder) instead of textView.setText(someString + spannableStringBuilder).

So my code now is like this:

SpannableStringBuilder str = new SpannableStringBuilder("paid | "
    +  decimalFormat.format(prizes[0]) + "€");
str.setSpan(new StyleSpan(BOLD), 7, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

money.setText(str);
0
Ready Android On

Issue is with you are setting a string at last of the money textview. It should be a spanned string.

Check with this one:

String sMoney = decimalFormat.format(prizes[0]) + "€";

SpannableString styledString = new SpannableString("paid | " + sMoney);

//This line of code is important because I added "paid | " in spannable string

styledString.setSpan(new StyleSpan(Typeface.BOLD), 7, styledString.length, 0);

money.setText(styledString);