javaandroidspannablestringtextstyle

Android SpannableString(Builder) does not apply style


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.


Solution

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