Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use argb color int value in Kotlin?

Tags:

android

kotlin

When I want to animate the textColor of TextView in Kotlin:

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.

like image 349
Hong Duan Avatar asked Jun 07 '17 07:06

Hong Duan


1 Answers

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)
like image 84
Alexander Romanov Avatar answered Oct 18 '22 23:10

Alexander Romanov