原文鏈接:http://www.reibang.com/p/0ac7c2c87ef9
DataBind普通的文字設置糙捺,我們都知道可以通過xml中的對象直接設置,那么圖片設置,或者其他另類數(shù)據(jù)處理呢饲握?這個時候不得不說另一顆聚氣寶石:BindingAdapter膀跌。我們以圖片加載來舉例:
1.創(chuàng)建對應的圖片適配器類
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.使用:三種加載圖片的使用,根據(jù)名稱不同邪乍,加載出來的效果就不同
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點出來对竣,容易出錯溺欧。