如何解决DataBinding - loadImage() 发生使用 Kotlin 的应用程序崩溃
我正在制作 RecyclerView + DataBinding + Kotlin 的示例 Android 应用。
当我创建“imageUrl”应用程序崩溃的注释绑定方法时。
我使用 Java 制作了相同的源项目。 而且没有问题。
只使用 Kotlin 出现错误。
RecyclerView 项目布局文件
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable name="index" type="int"/>
<variable name="viewModel" type="com.example.retrofitktex.viewmodel.DataVM"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dip"
android:orientation="horizontal"
android:padding="1dip">
<ImageView
android:id="@+id/img"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:padding="0dp"
android:layout_margin="0dp"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
app:imageUrl="@{viewModel.books[index].imageURL}"/>
</LinearLayout>
</layout>
'imageUrl'的注解绑定方法
companion object {
@BindingAdapter("bind:imageUrl")
fun loadImage(view: ImageView,imageUrl: String?) {
// source code
}
}
build.gradle(模块:app)
apply plugin: 'kotlin-kapt'
dependencies {
~
implementation 'org.projectlombok:lombok:1.16.14'
kapt 'org.projectlombok:lombok:1.16.14'
implementation "com.google.dagger:dagger:2.9"
kapt "com.google.dagger:dagger-compiler:2.9"
kaptTest "com.google.dagger:dagger-compiler:2.9"
compileOnly 'javax.annotation:jsr250-api:1.0'
}
build.gradle(项目)
buildscript {
ext.kotlin_version = "1.3.72"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "io.realm:realm-gradle-plugin:3.0.0"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
让我知道我错过了什么。 谢谢。
解决方法
从 bindingAdapter fun 的声明中移除 bind
。
这样做:
companion object {
@BindingAdapter("imageUrl")
fun loadImage(view: ImageView,imageUrl: String?) {
// source code
}
}
在 xml 中:
<ImageView
android:id="@+id/img"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:padding="0dp"
android:layout_margin="0dp"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
app:imageUrl="@{viewModel.books[index].imageURL}"/>
P.S:还要确保 viewModel.books[index]
不返回 null
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。