簡體   English   中英

數據綁定中的 Html.fromHtml - Android

[英]Html.fromHtml in DataBinding - Android

我在我的項目中使用了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))}"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM