0
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.

Community
  • 1
  • 1
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402

2 Answers2

1

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);
Ready Android
  • 3,529
  • 2
  • 26
  • 40
0

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);
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
  • 3
    Correct. The `+` operator is *string* concatenation, which converts `str` from a `SpannableStringBuilder` to a plain unformatted string. Use `TextUtils.concat()` to concatenate multiple `CharSequence` objects together, which works with `String` and `Spannable` objects, maintaining your spans. – CommonsWare Dec 26 '16 at 12:54
  • 2
    or `SpannableStringBuilder#insert()` method – pskink Dec 26 '16 at 12:55