我正在try 使用Android DataBinding Library设置自定义属性

Layout

<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.

Any pointers to solve it?

This happens only for custom attributes. The rest of the databindings work fine

推荐答案

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) { ... }

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) { ... }

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相关问答推荐

我可以检测一个函数是否在Kotlin中被递归调用(即,重入)吗?

如何让Gradle8+在编译Kotlin代码之前编译Groovy代码?然后把它们混合在一个项目中?

gradle 如何 Select 以-jvm结尾的库?

Kotlin SAM/功能接口抛出 AbstractMethodError

Kotlin:伴随对象内的函数扩展

Jetpack compose 可滚动表格

Spring webflux bean验证不起作用

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

如何从定义它们的类外部调用扩展方法?

在 Koin 中提供一个 Instance 作为其接口

在用Kotlin编写的Android库公共API中处理R8+JvmStatic Annotation+Lambda

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

空对象引用上的 TransitionSet ArrayList.size()

项目未与 Gradle 链接

如何从协程范围返回值

Kotlin out-projected 类型禁止使用

如何根据ArrayList的对象属性值从中获取最小/最大值?

旋转 kotlin 数组

Failure delivering result on activity result

使用 Kotlin 按字母对数组进行排序