Data Binding Formatted Strings Losing Format

Asked

Viewed 56 times

2

Apparently Data Binding for formatted strings does not work properly.

For example:

<string name="minhaString">Você tem um limite de <b>%s</b> reais.</string>

If I use Binding date text=@{string/minhaString(500)}

The expected result: You have a limit of 500 real.

The result obtained: You have a limit of 500 real.

That is, the Bold formatting part was not applied due to Binding date. The use of @{String.format(string/minhaString(500))} also does not apply Bold.

Someone knows how to fix this?

  • 1

    Have you tried using html? https://stackoverflow.com/a/51823945/10526030

2 answers

2


When you point to the string resource directly, Textview receives a Spanned type object, which implements the Charsequence interface and contains spans, elements that provide bold, italics, etc).

When you use Databinding, the Databinding API injects the values but returns a String object, which also implements Charsequence, but the Span elements were lost in the operation.

As @Murillo-Comino said, it is possible to reinterpret the String and generate an object that has Span through the Html class, according to https://stackoverflow.com/a/51823945/10526030.

However, the fromHtml method changed in API level 24 (Android N), so the most correct currently (for compatibility between different versions of Android) would be you use

HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY);

For this, it is necessary to include dependency in your project:

implementation 'androidx.core:core:1.0.1

Thus, you must insert: In the string.xml file

<string name="minhaString">Você tem um limite de <b>%s</b> reais.</string>

In the Layout file:

<import type="androidx.core.text.HtmlCompat"/>

In the component that receives the text:

android:text="@{HtmlCompat.fromHtml(@string/minhaString(500),HtmlCompat.FROM_HTML_MODE_LEGACY)}"

-1

Another possibility is you use a spannable, such as:

val span = SpannableString(this) span.setSpan(StyleSpan(Typeface.BOLD), startBold, endBold, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) return span

Browser other questions tagged

You are not signed in. Login or sign up in order to post.