Kotlin “toString()” 在 Android 数据绑定中不可用

Sam*_*hen 3 android kotlin kotlin-extension android-databinding android-jetpack

刚刚了解到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>
Run Code Online (Sandbox Code Playgroud)

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

Com*_*are 6

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()... 尝试@{Integer.valueOf(student.age).toString()}Integer.valueOf()会给你一个Integer装箱你的 Java实例int,并且Integer有一个toString()方法。这仍然与 Kotlin 没有任何关系,但它可以让您使用toString().

  • @Branddd:我建议你学习 Kotlin。使用 Jetpack Compose,UI 是在 Kotlin 中构建的,而不是通过布局资源 XML 文件构建。 (2认同)
  • @Branddd:“调用 findViewById 的性能代价很高”——数据绑定调用 `findViewById()`。`findViewById()` 是不可避免的——这只是一个问题,你是在调用它,还是你使用的其他代码在调用它。 (2认同)
  • @Branddd:“如果不是 dataBinding 那么是否有替代方案可以完成与 DataBinding 相同的工作?” -- 对于 Kotlin 中基于“View”的 Android 开发,其他现代方法是视图绑定和 Kotlin 合成访问器。其中,我更喜欢视图绑定。对于 Jetpack Compose,创建 UI 的方式完全不同,因此不再需要“findViewById()”及其之上的内容(数据绑定、视图绑定、Kotlin 合成访问器)。 (2认同)
  • @Branddd:请注意,Jetpack Compose 仍处于早期 alpha 状态。目前我不会向刚接触 Android 和 Kotlin 的人推荐它。现在,我建议学习经典的“View”系统。请记住,即使 Compose 发布,所有现有的 Android 应用程序也不会消失。我们将在现有项目中处理“View”很多年,因此即使在 Compose 流行之后,您今天学到的内容仍然有价值。 (2认同)