HTML formatting in new Android data binding library

Using the new data binding library for Android, can I use HTML formatting for TextView only through XML, or do I need to use Html.fromHtml programmatically?

+5
source share
3 answers

You must import the Html and then call the fromHtml method:

 <data> <import type="android.text.Html"/> </data><TextView android:text="@{Html.fromHtml(@string/my_html)}" android:layout_width="wrap_content" android:layout_height="wrap_content"/> 
+18
source

Conversions should not be performed in a view. A view model is designed to transform operations between your source model and your view.

Therefore, I would prefer to do it like this:

 <data> <variable name="viewModel" type="yourpackage.YourViewModel"/> </data><TextView android:text="@{viewModel.htmlText}" android:layout_width="wrap_content" android:layout_height="wrap_content"/> 

In your view model:

 private Model model; // your model public Spanned getHtmlText(){ return Html.fromHtml(model.htmlText); } 
+1
source

If you want to use a string with html tags and combine it with string parameters, this can be done as follows:

In the layout:

 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{activity.formattedString}" /> 

In your activity (for example):

 public CharSequence getFormattedString() { if(selectedItem == null) return null; String str = String.format(Html.toHtml(SpannedString.valueOf(this.getResources().getText(R.string.your_tagged_string))), parameter); return Html.fromHtml(str); } 
0
source

All Articles