Html.fromHtml in DataBinding - Android



我在项目中使用 from 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)}" />

但是当我更改为波纹管时,我崩溃了:

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

在我的string.xml

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

认为您需要先在 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))}" />
我认为

视图不应该有任何逻辑/转换来显示数据。我建议做的是为此创建一个 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);
}

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

<TextView
                android:id="@+id/bid_footer"
                style="@style/MyApp.TextView.Footer"
                android:htmlText="@{viewModel.bidFooter} />

其中 viewModel.bidFooter 具有获取带有文本的字符串/跨度/字符的逻辑,同时考虑到与上下文、活动等没有任何直接依赖

以下行在 Android N 中已弃用(API 级别 24(。

Html.fromHtml(content)

现在你应该提供两个参数(内容和标志(,如下所示:

Html.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)

所以我建议你使用如下@BindingAdapter

object BindingUtils {
@JvmStatic
@BindingAdapter("loadHtml")
fun loadHtml(textView: TextView, content: String?){
    if (!content.isNullOrEmpty()) {
        textView.text = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            Html.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)
        } else {
            Html.fromHtml(content)
        }
    }
}

}

并在您的 XML 文件中:

 <data>
    <import type="com.example.utils.BindingUtils"/>
</data>
<TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:loadHtml="@{String.format(@string/DateCreate,others.created))}"/>

最新更新