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

我已经在Fragment内部使绑定适配器静态可用,这基本上将我的按钮外观从“停止”更改为“播放”,反之亦然。

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

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

<?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()Boolean处翻转UIState

编译后,数据绑定编译器将引发以下错误:

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

我尝试过:

  1. 通过删除.gradle文件夹重建项目
  2. 正在寻找答案herehere
  3. 在扩展功能中删除了@JvmStatic注释
  4. 将扩展功能移至顶层,而不是Fragment的伴随对象。
it2011 回答:数据绑定编译器找不到提供的自定义绑定适配器

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

,

您需要将视图引用作为参数添加到BindingAdapter方法中。

 @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'
本文链接:https://www.f2er.com/3119521.html

大家都在问