Html.fromHtml in DataBinding - Android
I think that the view should not have any logic/transformation to display the data. What I'd recommend to do is creating a BindingAdapter for this:
@BindingAdapter({"android:htmlText"})
public static void setHtmlTextValue(TextView textView, String htmlText) {
if (htmlText == null)
return;
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(htmlText);
}
textView.setText(result);
}
Then within the layout call it as usual:
<TextView
android:id="@+id/bid_footer"
style="@style/MyApp.TextView.Footer"
android:htmlText="@{viewModel.bidFooter} />
Where viewModel.bidFooter has the logic to get the String/Spanned/Chars with the text, taking into consideration not having any direct dependence to context, activity, etc
Think you need to import html first in the xml
<data>
<import type="android.text.Html"/>
</data>
<TextView
android:id="@+id/txtDateCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{Html.fromHtml(String.format(@string/DateCreate,others.created))}" />
The line below is deprecated in Android N (API level 24).
Html.fromHtml(content)
Now you're supposed to provide two params (content and flag) like below:
Html.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)
So I'll suggest you use @BindingAdapter like below:
object BindingUtils {
@JvmStatic
@BindingAdapter("loadHtml")
fun loadHtml(textView: TextView, content: String?){
if (!content.isNullOrEmpty()) {
textView.text = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Html.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(content)
}
}
}
}
and in your XML file:
<data>
<import type="com.example.utils.BindingUtils"/>
</data>
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:loadHtml="@{String.format(@string/DateCreate,others.created))}"/>