BindingAdapter的學習可以去看官網,綁定適配器
在學習中,遇到一個問題,查了好多資料也沒解決,無意之間發現瞭解決方法,記錄一下
首先定義BindingAdapter方法,這個可以放在單獨的文件裏
@BindingAdapter("app:error")
fun error(text: TextView, error: String) {
text.text = error
}
也可以定義成這樣
class BindingAdapterUtil {
companion object{
@JvmStatic
@BindingAdapter("app:error")
fun error(text:TextView,error:String){
text.text=error
}
}
}
然後在佈局中引用
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:error="@{userOb.firstName}"
android:onClick="@{handlers::onClickFriend}"/>
重點來了,如果在引用裏邊,不使用@{},比如我使用
app:error="錯誤信息"
就會報
AAPT: error: attribute error (aka com.hzj.jetpackkotlin:error) not found.
所以,如果使用BindingAdapter,就要結合@{}表達式使用