Data Binding自定义属性

Data Binding自定义属性需要使用到BindingAdapter
什么是BindingAdapter
BindingAdapter用来设置布局中View的自定义属性,当使用该属性时,可以自定义其行为。

例如
@BindingAdapter(“android:bufferType”)
public static void setBufferType(TextView view, TextView.BufferType bufferType) {
view.setText(view.getText(), bufferType);
}
当一个方法加上@BindingAdapter注解后,就定义了一个BindingAdapter,注意方法的第一个参数是需要绑定到的View,第二个参数是绑定的属性值。
当定义完成后,此时我们就可以在布局的View中使用该属性,举例如下:

当TextView中加入了android:bufferType=”normal”后,setBufferType()方法就会被调用。

自定义图片加载的BindingAdapter

由于BindingAdapter的特性,我们就可以为ImageView自定义一个BindingAdapter,从而大幅简化图片加载的过程。
第一步,我们先新建一个ImageBindingAdapter的类,图片相关的BindingAdapter可以都定义在这个类里面:

public class ImageBindingAdapter {

@BindingAdapter("imageUrl")
public static void bindImageUrl(ImageView view, String imageUrl){
    RequestOptions options =
            new RequestOptions()
            .centerCrop()
            .dontAnimate();
    Glide.with(view)
            .load(imageUrl)
            .apply(options)
            .into(view);
}

}

定义好后,我们就可以直接在布局中使用这个属性了:

参考文档
1、Android开发教程 - 使用Data Binding(七)使用BindingAdapter简化图片加载
https://blog.csdn.net/SanCava/article/details/82624596

2、Android进阶十四:Databinding之@BindingAdapter和Component
https://blog.csdn.net/lixpjita39/article/details/79054052

你可能感兴趣的:(android)