首页 > 解决方案 > Kotlin “toString()” 在 Android 数据绑定中不可用

问题描述

刚学习DataBinding发现toString()Kotlin强大的内置功能不可用:

<layout 
    xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable
            name="student"
            type="com.example.databindingtest2.Student" />

    </data>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{student.name}"
        android:textColor="@android:color/black"
        android:textSize="30sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@{student.age.toString()}"    //doesn't work, age is integer
        android:textColor="@android:color/black"
        android:textSize="30sp" />

</layout>

我知道String.valueOf()会起作用,但这不是 Kotlin 的方式。任何帮助,将不胜感激。

标签: androidkotlinandroid-databindingandroid-jetpackkotlin-extension

解决方案


doesn't work, age is integer

Java 或 Kotlin 中都没有名为integer. 我猜那age是 Kotlin Int

cannot find method toString() in class int

数据绑定是用 Java 实现的,而不是 Kotlin。Java/Kotlin 互操作性与数据绑定编译器相结合,似乎将 KotlinInt转换为 Javaint原始类型。Java 原语不扩展Object也没有toString().

就个人而言,我建议不要投资于数据绑定。Jetpack Compose 将在一年左右的时间内淘汰数据绑定。

如果您仍希望使用数据绑定,最简单的解决方案是String.valueOf(). 当您说“这不是 Kotlin 方式”时,您使用的是数据绑定生成的 Java,而不是 Kotlin。

如果您仍然希望使用数据绑定,并且您坚持必须使用toString()... try @{Integer.valueOf(student.age).toString()}Integer.valueOf()会给你一个Integer装箱的Java实例int,并且Integer有一个toString()方法。这仍然与 Kotlin 无关,但它会让你使用toString().


推荐阅读