原文鏈接:http://www.itdecent.cn/p/0ac7c2c87ef9
DataBind普通的文字設(shè)置,我們都知道可以通過(guò)xml中的對(duì)象直接設(shè)置,那么圖片設(shè)置,或者其他另類數(shù)據(jù)處理呢?這個(gè)時(shí)候不得不說(shuō)另一顆聚氣寶石:BindingAdapter。我們以圖片加載來(lái)舉例:
1.創(chuàng)建對(duì)應(yī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ù)名稱不同,加載出來(lái)的效果就不同
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
特點(diǎn):
- 1.一次編寫(xiě),到處配置
- 2.省去xml中寫(xiě)控件id,也不用在java代碼中設(shè)置圖片加載方式
缺點(diǎn):
里面的item.imgUrl沒(méi)法直接通過(guò)item點(diǎn)出來(lái),容易出錯(cuò)。