DataBinding中的Html.fromHtml - Android

4 android android-databinding

dataBinding在我的项目中使用,当我贬低xml它的好工作时:

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

但当我改变为吼叫让我崩溃:

    <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))}" />
Run Code Online (Sandbox Code Playgroud)

在我的string.xml:

<resources>
<string name="DateCreate">open : <![CDATA[<b><font color=#FF0000>%s</b>]]></string>
</resources>
Run Code Online (Sandbox Code Playgroud)

deb*_*low 10

认为你需要先在xml中导入html

<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))}" />
Run Code Online (Sandbox Code Playgroud)


Car*_*iel 5

我认为视图不应该有任何逻辑/转换来显示数据。我建议做的是为此创建一个 BindingAdapter:

@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);
}
Run Code Online (Sandbox Code Playgroud)

然后在布局中像往常一样调用它:

<TextView
                android:id="@+id/bid_footer"
                style="@style/MyApp.TextView.Footer"
                android:htmlText="@{viewModel.bidFooter} />
Run Code Online (Sandbox Code Playgroud)

viewModel.bidFooter具有逻辑得到与文本字符串/跨区/字符数,考虑到没有任何直接依赖于上下文,活动等