小编Mil*_*rts的帖子

带有扩展方法的 Kotlin 数据绑定

我正在尝试在 Android 的数据绑定中使用 Kotlin 扩展方法。例如; 调用一个 onclick 处理程序。所以我做了这个代码:

posttest_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
Run Code Online (Sandbox Code Playgroud)

<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)}"
    >
[...]
Run Code Online (Sandbox Code Playgroud)

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
   }
}
Run Code Online (Sandbox Code Playgroud)

PostTestItemViewModelExtension.kt

fun PostTestItemViewModel.clicked(v: View) {
    this.postTitle.value = "clicked"
} …
Run Code Online (Sandbox Code Playgroud)

android kotlin kotlin-extension kotlin-android-extensions

4
推荐指数
1
解决办法
1856
查看次数