自定义属性:
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方法,再将返回值赋给引用。