android - 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 的方式。任何帮助,将不胜感激。
解决方案
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()
.
推荐阅读
- javascript - 如何在使用 Cloud Functions 触发的事件上推送通知
- c - 循环内循环不运行
- list - 方案:将列表作为参数映射到函数
- php - 无法创建 MYSQL 主键
- go - 如何为未知层次结构组成基本 ldap 字符串
- android - 无法将正确的照片 URL 上传到 Firebase
- java - Hibernate 保存瞬态实例
- react-native - native-base:左对齐 Picker 和 Input
- rasa-nlu - 如何使用 RASA NLU 提取不是相邻单词的实体
- reactjs - 如何选择和取消选择在 React 中使用 map 函数创建的表的动态创建的列 td,例如选择座位和取消选择