在嘗試使用 MVVM 架構時,使用 DataBinding 遇到了此問題 part2
一 Build 就會出錯,錯誤訊息如下
Found data binding errors.
****/ data binding error ****msg:Cannot find the getter for attribute 'android:background' with value type int on android.support.constraint.ConstraintLayout. file:XXX ****\ data binding error ****
我們很明顯的可以從訊息看出 background 的值 type 是 int
來看 layout.xml 檔我們是怎麼設的
android:background="@{myVm.circleCounter.backgroundColor}"
沒錯,這個 backgroundColor 我是訂義為 int
但查原碼發現,background 是接收 Drawable 的,因此出錯
// 原碼片段
public void setBackground(Drawable background) {
//noinspection deprecation
setBackgroundDrawable(background);
}
那該怎麼辦呢?
我們可以使用 @BindingConversion 的標簽來解決,如下
@BindingConversion
public static Drawable convertColorToDrawable(int drawable) {
return new ColorDrawable(drawable);
}
當 xml 有屬性不匹配的話
系統就會在全部有 @BindingConversion 標簽的方法中
尋找適合的方法做轉型
比如說這裡的 android:background 應該使用 Drawable 而不是 int
所以系統就會找到這個 method 來把 int 轉成 Drawable
注意:
也因為會在全部的 @BindingConversion 方法中尋找
所以方法加在專案的哪一個 class 都會生效喔