问题
I have been using data binding for the past few weeks and now am trying to use a two way data binding for a custom view with a 'value' attribute.
My problem is that I get the following error when building.
Cannot find a getter for <com.twisthenry8gmail.dragline.DraglineView app:value> that accepts parameter type 'long'
Now it was my understanding that the binding library will automatically use my public setters and getters however the most confusing part is adding a redundant inverse binding adapter seems to solve the problem? So I get the impression that it is using my setter without needing an adapter but this is not the case for the getter?
If someone could shed some light on this, or generally how the binding works in this instance it would be much appreciated. Here is my relevant code, please ask if you have any questions!
My custom view
class DraglineView(context: Context, attrs: AttributeSet) : View(context, attrs) {
...
var value = 0L
set(value) {
draggedValue = value
field = value
invalidate()
}
...
}
My view in the layout file
<com.twisthenry8gmail.dragline.DraglineView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:increment="@{viewmodel.type.minIncrement}"
app:minValue="@{viewmodel.type.minIncrement}"
app:value="@={viewmodel.target}" />
My seemingly redundant adapter
@InverseBindingAdapter(attribute = "value")
@JvmStatic
fun getValueTest(draglineView: DraglineView): Long {
return draglineView.value
}
My attribute changed adapter
@BindingAdapter("valueAttrChanged")
@JvmStatic
fun setDraglineListener(draglineView: DraglineView, listener: InverseBindingListener) {
draglineView.valueChangedListener = {
listener.onChange()
}
}
回答1:
The problem is that databinding system doesn't know when the view changes the value.
InverseBindingAdapter not only describes how to retrieve the value from the view, but it also defines an optional event property which will receive an InverseBindingListener instance. The default event name is the attribute name suffixed with "AttrChanged".
Now let's look at your setDraglineListener()
adapter. It processes valueAttrChanged
attribute added by InverseBindingAdapter
and receives InverseBindingListener
. The only thing is left is to notify the listener when the value is changed by calling listener.onChange()
;
来源:https://stackoverflow.com/questions/62012093/android-data-binding-cannot-find-getter-for-that-accepts-parameter-type-lo