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,就要结合@{}表达式使用