Kotlin自定义属性数据绑定 [英] Kotlin custom attribute databinding
问题描述
我正在尝试使用 Android DataBinding库设置自定义属性一个> 在我的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:
中的BindingAdapter不是静态的,需要使用从DataBindingComponent检索的对象.如果您不使用带有DataBindingComponent的膨胀方法,请使用DataBindingUtil.setDefaultComponent或将所有BindingAdapter方法设为静态.
A BindingAdapter in in 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) { ... }
这篇关于Kotlin自定义属性数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!