[DataBinding] Adding HTML-formatted text to TextView in databinding


Writing time : 2021-10-25 10:51:53

Learn how to add HTML-formatted text to TextView in Data Binding.
You'll also learn how to add text using Html.from and how to use String.format together.

HTML import

Import the layout.xml android.text.Html class in the data tag.

<layout xmlns:android="http://schemas.android.com/apk/res/android"  
    ...  
  
    <data>  
        <import type="android.text.Html"/>  
        ...  
    </data>  
  


Using Html.from in XML

string.xml

Declare a string in string.xml.

<string name="text_hello">hello><![CDATA[Hello <font color=#1dad50><strong>Android</strong></font>]]></string>  

layout.xml

Use the string declared in string.xml.

<androidx.appcompat.widget.AppCompatTextView  
    android:id="@+id/textItemCount"  
    style="@style/TextBlackBigWeightWrapBold"  
    android:text="@{Html.fromHtml(@string/text_hello)}"/>  


Using Html.from with String.format in XML

string.xml

Declare a string in the format format string in string.xml.

<string name="text_hello">hello><![CDATA[Hello <font color=#1dad50><strong>%1$s</strong></font>]]></string>  

Use the string declared in string.xml by using the String.format statement.

layout.xml

<androidx.appcompat.widget.AppCompatTextView  
    android:id="@+id/textItemCount"  
    style="@style/TextBlackBigWeightWrapBold"  
    android:text="@{Html.fromHtml(String.format(@string/text_hello,viewmodel.userName))}"/>