我正在尝试在 Android 的数据绑定中使用 Kotlin 扩展方法。例如;调用 onclick 处理程序。所以我编写了这段代码:
posttest_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<data>
<import type="android.view.View"/>
<import type="com.example.test.post.posttest.PostTestItemViewModelExtensionKt" />
<variable
name="viewModel"
type="com.example.test.post.posttest.PostTestItemViewModel" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:clickable="true"
android:onClick="@{(view) -> viewModel.clicked(view)}"
>
[...]
PostTestItemViewModel.kt
open class PostTestItemViewModel : ViewModel() {
val postTitle = MutableLiveData<String>()
val postBody = MutableLiveData<String>()
/**
* Binds the required properties/entities to this ViewModel
*/
fun bind(post: Post) {
postTitle.value = post.title
postBody.value = post.body
}
}
PostTestItemViewModelExtension.kt
fun PostTestItemViewModel.clicked(v: View) {
this.postTitle.value = "clicked"
}
因此,当我将单击的方法放置在视图模型中时,它会按照应有的方式完美运行。但是,当我将其创建为扩展方法时,我在编译时收到以下错误:
e:[kapt]发生异常:android.databinding.tool.util.LoggedErrorException:发现数据绑定错误。
在类中找不到单击的方法(android.view.View)...PostItemViewModel
我已经尝试过不同的事情,例如更改android:onclick
tag to PostTestItemViewModelExtensionKt
代替viewModel
。不幸的是,所有的事情似乎都不起作用。所以看起来扩展方法是在数据绑定发生后生成的。有办法解决这个问题还是我仍然做错了什么?或者只是不可能绑定扩展方法?
我正在使用 Kotlin 版本 1.2.71,gradle 3.2.0 并且有databinding { enabled = true }
and kapt { generateStubs = true }
添加到我的 .gradle 中,并拥有插件kotlin-android
, kotlin-android-extensions
and kotlin-kapt
定义的。