@BindingAdapter 註解
databinding中自定義屬性依賴於註解 @BindingAdapter
作用於方法(和類無關,這個自定義屬性的方法可以寫在任何地方)
它定義了xml的屬性賦值的java實現(註解的方法中就是我們對這個控件進行處理)
方法必須爲公共靜(public static)方法,可以有一到多個參數。
簡單實用
直接上代碼
//“app:imgUrl” 這就是在xml中的屬性
@android.databinding.BindingAdapter("app:imgUrl")
public static void setImgUrl(ImageView imageView, String url) {
GlideApp.with(imageView)
.load(url)
.into(imageView);
}
xml 中使用
<ImageView
android:id="@+id/img_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
app:imgUrl="@{user.url}"
/>
多參數使用
繼續上代碼
@android.databinding.BindingAdapter(value = {"app:imgUrl", "app:placeholder"}, requireAll = false)
public static void loadImg(ImageView imageView, String url, Drawable placeholder) {
GlideApp.with(imageView)
.load(url)
.placeholder(placeholder)
.into(imageView);
}
xml中代碼
<ImageView
android:id="@+id/img_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
app:imgUrl="@{user.url}"
app:placeholder="@{@drawable/ic_launcher_background}"
/>
這裏 requireAll = false 表示我們可以使用這兩個兩個屬性中的任一個或同時使用,如果requireAll = true 則兩個屬性必須同時使用,不然報錯。默認爲 true。
xml 中@{@drawable/ic_launcher_background} 引用的是資源文件中的圖片
使用屬性舊值
@BindingAdapter 自定義屬性可以使用屬性舊值,即上一次設置的屬性值
上代碼
@android.databinding.BindingAdapter(value = {"app:imgUrl", "app:placeholder"}, requireAll = false)
public static void loadImg(ImageView imageView, String oldUrl, Drawable oldError, String newUrl, Drawable newError) {
GlideApp.with(imageView)
.load(newUrl)
.placeholder(oldError)
.into(imageView);
}
這裏要注意一點:如果是多個屬性,那麼方法的參數必須要把所有的屬性的舊值列舉出來,然後在列舉屬性新值。這個順序是不能亂的。並不是一個屬性舊值跟一個屬性新值。