kotlin - DataBinding - loadImage() 使用 Kotlin 发生 App 崩溃
问题描述
我正在制作 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
}
}
让我知道我错过了什么。谢谢你。
解决方案
bind
从 bindingAdapter fun 的声明中删除。这样做:
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}"/>
PS:也确保viewModel.books[index]
不退货null
推荐阅读
- node.js - ORM:Sequelize:多对多关系查询
- .htaccess - htaccess 阻止并允许来自相同域名的站点
- elasticsearch - Elasticsearch 移除字段性能
- javascript - 表排序、过滤等 Matt Kruse 的库
- javascript - 数组推送功能无法正常工作
- python - 如何将 Python 数据集(之前从 IDL 导出)保存回 IDL 格式
- python - 星期结束日期,星期日是一周的第一天
- ios - 即使设置了委托,MKMapview 委托也从未调用过
- asp.net-core - 在标签助手之间传递信息?
- ssms - SSMS 18 工具 -> 选项 -> 环境 -> 选项卡和 Windows 选项丢失