Html.fromHtml in DataBinding - Android

天涯浪子 提交于 2020-04-10 17:45:22

问题


I am using from dataBinding in my project,when I have bellow xml it good work :

    <TextView
        android:id="@+id/txtDateCreate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{String.format(@string/DateCreate,others.created)}" />

But when I change to bellow get me crash:

    <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))}" />

Here in my string.xml :

<resources>
<string name="DateCreate">open : <![CDATA[<b><font color=#FF0000>%s</b>]]></string>
</resources>

回答1:


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))}" />



回答2:


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



来源:https://stackoverflow.com/questions/43886956/html-fromhtml-in-databinding-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!