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?
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.
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.
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.
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.
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"/>
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With