DataBinding進階(四)

自定義屬性:

Databinding提供了@BindingAdapter(“屬性名”)註解來完成自定義屬性。 如果要綁定多個屬性,屬性之間用英文的逗號隔開,例如@BindingAdapter(“bind:image” , “bind:test” )
在JavaBean中定義如下方法:

@BindingAdapter("show")
public static void showIcon(ImageView iv, String imgUrl) {
    if (!TextUtils.isEmpty(imgUrl)) {
        Glide.with(iv)
                .load(imgUrl)
                .into(iv);
    }
}

  @SuppressLint("ResourceType")
    @BindingAdapter("show")
    public static void showIcon(ImageView iv, @IdRes int ivID) {
        if (ivID > 0) {
            Glide.with(iv)
                    .load(ivID)
                    .into(iv);
        }
    }

佈局中引用時記得先加上自定義命名空間

xmlns:app="http://schemas.android.com/apk/res-auto"

在控件中使用

<ImageView
     style="@style/WrapWrap"
     app:show="@{test.url}"/>

這樣,運行時就會自動加載TestModel中設置的url獲取圖片展示到控件上。

            <ImageView
                android:id="@+id/iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:show="@{ivID}" />
mBinding.setIvID(R.mipmap.ic_launcher_round); 直接設置ivId即可顯示對應圖像

數據轉換

在佈局中引用的數據,如果要求的類型與獲取的類型不一致,需要開發者自行轉換。 
android:text=”要求是CharSequence類型”,使用String.valueOf()轉換; 
還有一種非常實用的轉換:

<TextView
     style="@style/WrapWrap"
     android:text="@{String.valueOf(observableMap[key])}"
     android:visibility="@{error?android.view.View.VISIBLE:android.view.View.INVISIBLE}"
     android:textColor="@{error?@color/red:@color/green}"
     android:background="@{error?@color/green:@color/red}"
     />

這裏根據error是否爲true,判斷了TextView的顯示隱藏、背景以及文字的顏色。 
android:visibility中可以將android.view.View使用import導包,寫成

//data節點下
<import type="android.view.View"/>
//引用
android:visibility="@{error?View.VISIBLE:View.INVISIBLE}"

注意同一屬性只能引用同種類型的數據,即android:background中error爲true/false,引用@color只能引用@color,引用@drawable只能引用@drawable,不能同時@color和@drawable混用(可能你混用還是能運行,但是一改變error的值切換的時候就會“嘣嘣嘣”了)。


自動轉換 
Databinding提供了自動轉換註解@BindingConversion,還是來個栗子:

佈局:

<variable
     name="time"
     type="java.util.Date"/>

<TextView
     style="@style/WrapWrap"
     android:text="@{time}"/>

代碼:

binding.setTime(new Date());

直接運行,當然會報錯,關鍵在這:

public class MyDateConverter {

    @BindingConversion
    public static String convertDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        return sdf.format(date);
    }

}

convertDate方法你可以隨意放,在哪個類中都行,主要是@BindingConversion註解會在代碼編譯的時候,佈局中任意與convertDate參數類型一致的引用,先執行convertDate方法,再將返回值賦給引用。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章