数据绑定编译器找不到提供的自定义绑定适配器

Data Binding Compiler cannot find custom binding adapter provided

我在我的 Fragment 中静态提供了一个绑定适配器,它基本上将我的按钮外观从 "Stop" 更改为 "Play",反之亦然。

companion object {
        @BindingAdapter("playState")
        fun Button.setPlayState(item: UIState) {
            item.let {
                if (it.isPlaying) {
                    setText("Stop")
                    setBackgroundColor(ContextCompat.getColor(context, R.color.colorStop))
                } else {
                    setText("Play")
                    setBackgroundColor(ContextCompat.getColor(context, R.color.colorPlay))
                }
            }
        }
    }

这是我的布局文件。我已经为它提供了数据class。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <!-- stuff here -->
        <variable
            name="viewmodel"
            type="com.mypackage.ui.ViewModel"/>
        <variable
            name="uistate"
            type="com.mypackage.ui.UIState" />
    </data>
    <!-- layout, buttons, and more stuff here. Just pay attention to this following button -->
     <Button
            android:id="@+id/play_button"
            android:layout_width="150sp"
            android:layout_height="75sp"
            android:layout_marginTop="20sp"
            android:onClick="@{() -> viewmodel.onPlayClicked()}"
            android:text="@string/play_button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.498"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/minus_layout"
            app:layout_constraintVertical_bias="0.026"
            app:playState="@{uistate}"/>


</layout>

UIState 本身就很明显了。

data class UIState(var isPlaying: Boolean)

并且 () -> viewmodel.onPlayClicked()UIState 翻转 Boolean

编译后,数据绑定编译器抛出此错误:

Cannot find a setter for <android.widget.Button app:playState> 
that accepts parameter type 'com.mypackage.ui.UIState'

我试过了:

  1. 通过删除 .gradle 文件夹重建项目
  2. 正在寻找答案here and
  3. 删除了扩展函数中的 @JvmStatic 注释
  4. 将扩展函数移至顶层而不是 Fragment 的伴随对象。

您不必使用 @JvmStatic,因为您使用的是 Kotlin 扩展功能。

您需要将视图引用作为参数添加到绑定适配器方法中。

 @BindingAdapter("playState")
    fun setPlayState(button:Button,item: UIState) {
        //do your work here
    }

你的命名空间

xmlns:app="http://schemas.android.com/apk/res-auto"

自定义绑定适配器是错误的。请使用命名空间

xmlns:app="http://schemas.android.com/tools"

由于 app:playState 不在您指定的名称空间中,因此无法正常工作

我想你错过了在 gradle

中添加 kotlin 插件
apply plugin: 'kotlin-kapt'