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="@{[email protected]/red:@color/green}"
android:background="@{[email protected]/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方法,再將返回值賦給引用。