当我想在Kotlin 制作TextView中的textColor的动画时:

val animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF, 0xFFC953BE)

this error occurs:

Error:(124, 43) None of the following functions can be called with the arguments supplied:
public open fun <T : Any!> ofInt(target: TextView!, xProperty: Property<TextView!, Int!>!, yProperty: Property<TextView!, Int!>!, path: Path!): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun <T : Any!> ofInt(target: TextView!, property: Property<TextView!, Int!>!, vararg values: Int): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(target: Any!, propertyName: String!, vararg values: Int): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(target: Any!, xPropertyName: String!, yPropertyName: String!, path: Path!): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(vararg values: Int): ValueAnimator! defined in android.animation.ObjectAnimator

Seems that the value 0xFF8363FF and 0xFFC953BE cannot be cast to Int in Kotlin, however, it's normal in Java:

ObjectAnimator animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF, 0xFFC953BE);

Any ideas? Thanks in advance.

推荐答案

0xFF8363FF (as well as 0xFFC953BE) is a Long, not an Int.

You have to cast them to Int explicitly:

val animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF.toInt(), 0xFFC953BE.toInt())

The point is that the numeric value of 0xFFC953BE is 4291384254, so it should be stored in a Long variable. But the high bit here is a sign bit, that denotes a negative number: -3583042 which can be stored in Int.

And that's the difference between two languages. In Kotlin you should add the - sign to denote negative Int which is not true in Java:

// Kotlin
print(-0x80000000)             // >>> -2147483648 (fits into Int)
print(0x80000000)              // >>>  2147483648 (does NOT fit into Int)

// Java
System.out.print(-0x80000000); // >>> -2147483648 (fits into Integer)
System.out.print(0x80000000);  // >>> -2147483648 (fits into Integer)

Kotlin相关问答推荐

测试Compose Multiplatform UI时,为另一个文件设置ComposeRule()

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

为什么Kotlin有次构造函数和init块?

在 map 中查找键与在 kotlin 中查找 firstOrNull

Gradle:无法创建 ExtensiblePolymorphicDomainObjectContainer

Ktor 在 Heroku 上的 CORS 问题,但在本地没有

如何访问嵌套在另一个 map 中的 map 中的值(在 kotlin 中)

Kotlin 可空泛型

我可以在 Kotlin 中使用接口类型作为构造函数参数吗

为什么在 Kotlin 中调用私有构造函数会导致错误为无法访问 是什么?

kotlin,如何从函数返回类类型

使用 Kotlin 创建新目录,Mkdir() 不起作用

将多个 Kotlin 流合并到一个列表中,而无需等待第一个值

用mockk验证属性设置程序吗?

从片段(fragment)中的点击事件启动协同程序

Tornadofx - 如何在每个实例上将参数传递给 Fragment

Kotlin中的Memoization功能

类型不匹配推断类型为单位,但应为空

在 kotlin 中,如何将主构造函数中的属性设置器设为私有?

如何在 Kotlin 中生成 MD5 哈希?