Android工具集

DataBind第三篇:聚气宝石BindingAdapter

2019-06-22  本文已影响1人  Small_Cake

原文链接: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

特点:

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

上一篇下一篇

猜你喜欢

热点阅读