Kotlin 自定义属性数据绑定 [英] Kotlin custom attribute databinding
问题描述
我正在尝试使用 Android 数据绑定库一>在我的 Kotlin 项目中是这样的:
I am trying to set custom attribute using the Android DataBinding Library in my Kotlin project like this:
<ImageView
android:id="@+id/imgView"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:adjustViewBounds="true"
app:imageUrl="@{segment.url}"/>
代码
class Utils {
companion object {
@BindingAdapter("bind:imageUrl")
@JvmStatic
fun loadImage(view: ImageView, url:String)
{Picasso.with(view.context).load(url).error(R.drawable.error).into(view)}
}
}
我得到的运行时错误是:
The runtime error I get is:
A BindingAdapter in in <package.Utils.Companion> 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.
有什么解决办法吗?
这只发生在自定义属性上.其余的数据绑定工作正常
This happens only for custom attributes. The rest of the databindings work fine
推荐答案
只需将函数保持在顶层,不需要类或伴生对象,它会起作用,因为 Kotlin 中的顶层函数转换为名为 Class 的静态成员函数作为 FileNameKt
除非被 @file:JvmName
注释覆盖
Just keep function on the top level, no class or companion object needed, it will work since top-level functions in Kotlin translated to static member functions of Class named as FileNameKt
unless overridden by @file:JvmName
annotation
@BindingAdapter("imageUrl")
fun loadImage(view: ImageView, url:String) { ... }
另一种选择是将扩展函数注释为 @BindingAdapter
,它会起作用,因为字节码签名将与 DataBindings 预期的签名完全匹配(生成的方法仍将接受扩展类的对象作为第一个参数),函数也应该保持顶级
One more option is to annotate Extension Function as @BindingAdapter
, it will work since in bytecode signature will exactly match signature expected by DataBindings(generated method will still accept an object of the extended class as the first argument), the function should remain top level as well
@BindingAdapter("imageUrl")
fun ImageView.loadImage(url:String) { ... }
另一种选择是将 BindingAdapter
与扩展属性结合起来,如下所示:
One more option is to combine BindingAdapter
with the extension property like following:
@set:BindingAdapter("visible")
var View.visible
get() = visibility == VISIBLE
set(value) {
visibility = if (value) VISIBLE else GONE
}
这篇关于Kotlin 自定义属性数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!