Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML formatting in Android's new data binding library

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

like image 489
janoliver Avatar asked Aug 03 '15 01:08

janoliver


People also ask

Is data binding good in Android?

Using data binding can lead to faster development times, faster execution times and more readable and maintained code. Android data binding generates binding classes at compile time for layouts.

What are the data binding types in Android?

In Android, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.

What is DataBindingUtil in Android?

DataBindingUtil.setContentView(this, R.layout.activity_main) DataBindingUtil is a Utility class to create ViewDataBinding from layouts. A binding class is generated for each layout file. The default naming convention used for the generated class is based on the name of the layout file.

What is data binding with example?

Data binding can also mean that if an outer representation of the data in an element changes, then the underlying data can be automatically updated to reflect the change. For example, if the user edits the value in a TextBox element, the underlying data value is automatically updated to reflect that change.


2 Answers

You must import 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"/>
like image 73
Thomas G. Avatar answered Sep 28 '22 03:09

Thomas G.


In case if you want to use string with html tags and combine it with string parameters, it could be done in a such way:

In layout:

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

In your activity (for ex):

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);
}
like image 36
Fragment Avatar answered Sep 28 '22 02:09

Fragment