DataBind第三篇:聚气宝石BindingAdapter

原文链接:https://www.jianshu.com/p/0ac7c2c87ef9

DataBind普通的文字设置,我们都知道可以通过xml中的对象直接设置,那么图片设置,或者其他另类数据处理呢?这个时候不得不说另一颗聚气宝石:BindingAdapter。我们以图片加载来举例:

1.创建对应的图片适配器类
public class ImageBindingAdapter {
    //图片加载绑定为:普通图片
    @BindingAdapter("imageUrl")
    public static void bindImageUrl(ImageView view, String imageUrl){
        RequestOptions options = new RequestOptions()
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .centerCrop();
        Glide.with(view)
                .load(imageUrl)
                .apply(options)
                .into(view);
    }
    //图片加载绑定为:圆形裁剪图片
    @BindingAdapter("imageCircleUrl")
    public static void bindImageCircleUrl(ImageView view, String imageUrl){
        RequestOptions options = new RequestOptions()
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .circleCrop();
        Glide.with(view)
                .load(imageUrl)
                .apply(options)
                .into(view);
    }
    //图片加载绑定为:圆角图片
    @BindingAdapter("imageRoundUrl")
    public static void bindImageRoundUrl(ImageView view, String imageUrl){
        RequestOptions options = new RequestOptions()
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .transform(new RoundedCorners(8));
        Glide.with(view)
                .load(imageUrl)
                .apply(options)
                .into(view);
    }
}
2.使用:三种加载图片的使用,根据名称不同,加载出来的效果就不同

a. 普通图片

        <ImageView
            android:layout_width="200dp"
            android:layout_height="200dp"
            app:imageUrl="@{item.imgUrl}" />

b. 圆形图片

        <ImageView
            android:layout_width="200dp"
            android:layout_height="200dp"
            app:imageCircleUrl="@{item.imgUrl}" />

c. 圆角图片

        <ImageView
            android:layout_width="200dp"
            android:layout_height="200dp"
            app:imageRoundUrl="@{item.imgUrl}" />

三种效果如下:

效果abc

特点:

  • 1.一次编写,到处配置
  • 2.省去xml中写控件id,也不用在java代码中设置图片加载方式

缺点:
里面的item.imgUrl没法直接通过item点出来,容易出错。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。