Databinding搭配kotlin使用时与java有些区别,除了需要使用kapt依赖之外,由于kotlin没有static的特性和null-safe检查,还是踩了不少坑的,写个博客记录下。
业务场景:给ImageView添加一个自定义属性imageUrl,处理网络图片加载,xml代码如下:
<ImageView
android:id="@+id/title_img"
android:layout_width="200mm"
android:layout_height="100mm"
android:background="#66ccff"
android:scaleType="fitCenter"
app:imageUrl="@{vm.logoUrl}"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
之前用java的时候是这么处理的:
public class ImageBinds {
@BindingAdapter("imageUrl")
public static void bindImgUrl(ImageView imageView, String url) {
GlideApp.with(imageView.getContext())
.load(url)
.placeholder(R.drawable.ic_launcher_background)
.fitCenter()
.into(imageView);
}
}
直接把这个文件Convert Java File to Kotlin File
如下:
object ImageBinds {
@BindingAdapter("imageUrl")
fun bindImgUrl(imageView: ImageView, url: String) {
GlideApp.with(imageView.context)
.load(url)
.placeholder(R.drawable.ic_launcher_background)
.fitCenter()
.into(imageView)
}
}
编译没问题,启动应用报错Caused by: java.lang.IllegalStateException: Required DataBindingComponent is null in class ActivityMainBinding. A BindingAdapter in com.shouzhan.quickpush.binding.ImageBinds is not static and requires an object to use, retrieved from the DataBindingComponent. If you don't use an inflation method taking a DataBindingComponent, use DataBindingUtil.setDefaultComponent or make all BindingAdapter methods static.
这是由于自动转换成kotlin时丢失了static,给方法添加@JvmStatic
注解后再次编译运行,
这次报另一个错误,Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter url
这是由于url参数没有做可空处理,最终修改后如下:
object ImageBinds {
@BindingAdapter("imageUrl")
@JvmStatic
fun bindImgUrl(imageView: ImageView, url: String?) {
GlideApp.with(imageView.context)
.load(url)
.placeholder(R.drawable.ic_launcher_background)
.fitCenter()
.into(imageView)
}
}
编译后正常运行
网友评论