有没有可能将扩展功能与数据绑定一起使用?

<data>
    <import type="my.package.domain.country.model.City.streetName" />

    <variable
        name="city"
        type="my.package.domain.country.model.City" />
</data>

<TextView
    android:id="@+id/city"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{city.street.streetName()}" />

my.package.domain.country.model.city

data class City(
        val id: String,
        val street: Street
) 

fun City.streetName(): String = street.houseNumber

错误

[kapt] An exception occurred: android.databinding.tool.util.Logged错误Exception: Found data binding errors. ****/ data binding error ****msg:cannot find method streetName() in class my.package.domain.country.model.City

Thanks ;)

推荐答案

您必须先将CityKt导入到XML中

<import type="my.package.domain.country.model.CityKt" />

int the data section then you can use it like this

<TextView
  android:id="@+id/city"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@{CityKt.streetName(city)}" />

如果你回顾CityKt,你会发现有一个静态Java方法,其中City是第一个参数

Kotlin相关问答推荐

"Kotlin中的表达式

使函数同时挂起和取消挂起

有没有办法在 jetpack compose 中将 TextField 密码点图标增加得更大?

在 Kotlin 中实现并输入 Either

如何在 Kotlin 中初始化 Short 数组?

将一个列表元素分组为多个组(indexBy)

Kotlin SAM/功能接口抛出 AbstractMethodError

listOf() 返回 MutableList

使用 Hilt 注入 CoroutineWorker

Kotlin 中 lambda 表达式中的默认参数

是否可以在 kotlin 中嵌套数据类?

如何在 kotlin 的片段类中更改 ActionBar 标题?

Intellij 显示 build.gradle.kts 中的每一行都是红色的

如何在Android Studio 4.1中默认启用Kotlin Android扩展

在Kotlin中将列表转换为对的惯用方法

Kotlin 中内部可见性修饰符的范围

有没有办法在Kotlin中设置一个私有常量

从另一个列表创建一个列表

Kotlin:获取文件的扩展名,例如.txt

Kotlin 中的填充字符串