【发布时间】:2018-04-08 20:19:37
【问题描述】:
这是我的BindingAdapter:
@BindingAdapter(value = *arrayOf("bind:commentsAdapter", "bind:itemClick", "bind:avatarClick", "bind:scrolledUp"), requireAll = false)
fun initWithCommentsAdapter(recyclerView: RecyclerView, commentsAdapter: CommentsAdapter,
itemClick: (item: EntityCommentItem) -> Unit,
avatarClick: ((item: EntityCommentItem) -> Unit)?,
scrolledUp: (() -> Unit)?) {
//Some code here
}
initWithCommentsAdapter 是顶级函数
这是我的布局(必不可少的部分):
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="some.example.path.CommentsViewModel"/>
<variable
name="commentsAdapter"
type="some.example.path.CommentsAdapter"/>
</data>
<android.support.v7.widget.RecyclerView
...
bind:avatarClick="@{(item) -> viewModel.avatarClick(item)}"
bind:itemClick="@{viewModel::commentClick}"
bind:commentsAdapter="@{commentsAdapter}"
bind:isVisible="@{viewModel.commentsVisibility}"
bind:scrolledUp="@{() -> viewModel.scrolledUp()}"
/>
</layout>
当我在布局中为 lambda 分配 kotlin 方法调用时,在构建过程中出现这样的错误:
e: java.lang.IllegalStateException: failed to analyze:
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:cannot find method avatarClick(java.lang.Object)
in class some.example.path.CommentsViewModel
****\ data binding error ****
或者如果我通过引用分配方法:
e: java.lang.IllegalStateException: failed to analyze:
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Listener class kotlin.jvm.functions.Function1
with method invoke did not match signature of any method viewModel::commentClick
file:C:\Android\Projects\...\fragment_comments.xml
loc:70:12 - 83:17
****\ data binding error ****
但我有这样的方法,类型正确,而不是 Object
问题
如何在布局中为 Kotlin 中的自定义 @BindingAdapter 分配 Kotlin lambda?
编辑
viewModel的相关部分:
class CommentsViewModel(model: CommentsModel): BaseObservable() {
//Some binded variables here
...
fun commentClick(item: EntityCommentItem) {
//Some code here
}
fun avatarClick(item: EntityCommentItem) {
//Some code here
}
fun scrolledUp() {
//Some code here
}
...
}
变量绑定工作得很好
【问题讨论】:
-
能把
CommentsViewModel的相关部分加进去吗? -
我从 viewModel 类中添加了一些相关代码
-
与 BindingAdapter 中的类型相同
-
你找到解决办法了吗?
-
很遗憾没有。我使用了解决方法。我只是通过一些方法传递一个对象。但那是很久以前的事了。我已经忘记了。
标签: android kotlin android-databinding