【问题标题】:Android two way data binding on custom View. Cannot find getterAndroid 自定义 View 上的双向数据绑定。找不到吸气剂
【发布时间】:2020-02-28 16:26:08
【问题描述】:

我正在自定义视图上实现两种方式的数据绑定。我关注了official android developers,但仍然无法正常工作。我有一个旋钮,可以控制 value 属性内的整数值。

class ControlKnob(context: Context, attributeSet : android.util.AttributeSet) : RelativeLayout(context, attributeSet), IUIControl {
    companion object {
        @JvmStatic
        @BindingAdapter("value")
        fun setValue(knob : ControlKnob, value : Int) {
            if(knob.value != value) {
                knob.value = value
            }

        }

        @JvmStatic
        @InverseBindingAdapter(attribute = "value")
        fun getValue(knob : ControlKnob) : Int {
            return knob.value
        }

        @JvmStatic
        @BindingAdapter("app:valueAttrChanged")
        fun setListeners( knob : ControlKnob, attrChange : InverseBindingListener) {
            knob.setOnProgressChangedListener {
                attrChange.onChange()
            }
        }
    }
    var value : Int = -1
    set(value) {
        field = value
        valueView.text = stringConverter.invoke(value)
    }
....
....
}

内部布局我是这样使用的:

<cz.abc.def.package.controls.ControlKnob
                    android:id="@+id/knob"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_row="0"
                    android:layout_column="0"
                    app:value="@={viewModel.value}"
                    app:label="Knob" />

还有我的视图模型:

@Bindable
fun getValue() : Int {
    return someValue
}

fun setValue(value : Int) {
    someValue = value

}

但我仍然无法编译它。我明白了

Cannot find a getter for cz.abc.def.package.controls.ControlKnob app:value that accepts parameter type 'int'

If a binding adapter provides the getter, check that the adapter is annotated correctly and that the parameter type matches.

这可能是什么原因?

【问题讨论】:

    标签: android kotlin android-databinding


    【解决方案1】:

    也许您的侦听器绑定适配器错误?根据the documentation,事件监听器BindingAdapter 的值应该是"android:valueAttrChanged",而你有"app:valueAttrChanged"

    【讨论】:

    • 将侦听器绑定适配器更改为 android:valueAttrChanged 没有帮助。仍然有同样的错误
    【解决方案2】:

    我想通了。事实证明,代码没有问题。我在 gradle 构建文件中缺少 apply plugin: 'kotlin-kapt' 。在我将此行添加到模块中的 build.gradle 之后,它就可以工作了。

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多