出身背景

在Java中,我可以使用TextView的标准十六进制值直接更改TextView的文本 colored颜色 :

    textView.setTextColor(0xffffffff); //white
    textView.setTextColor(0x00000000); //transparent
    textView.setTextColor(0xff000000); //black
    textView.setTextColor(0xff0000ff); //blue
    //etc...

Very easy...

问题

On Kotlin, if I try to write such a thing, I get with a weird build error:

Error:(15, 18) None of the following functions can be called with the arguments supplied: public open fun setTextColor(p0: ColorStateList!): Unit defined in android.widget.TextView public open fun setTextColor(p0: Int): Unit defined in android.widget.TextView

我试过的是

I tried to search about this over the Internet, and I couldn't see anything special about hexa-decimal values. Seems the same like on Java:

https://kotlinlang.org/docs/reference/basic-types.html

Then I decided to just write in Java, and convert to Kotlin. The result is very unreadable in terms of the color value:

    textView.setTextColor(-0x1) //white
    textView.setTextColor(0x00000000) //transparent
    textView.setTextColor(-0x1000000) //black
    textView.setTextColor(-0xffff01) //blue

在我看来,用于Kotlin的整数的十六进制值似乎是有符号的,而在Java上它会自动转换为有符号的,因此这会导致值的翻转,并且需要在需要时设置负号.

我能想到的唯一一件事,仍然能让它读得很好的,就是这样的东西:

textView.setTextColor(Integer.parseUnsignedInt("ffff0000",16));

However, this has multiple disadvantages:

  1. 时间要长得多.
  2. It converts a String, so it's much less efficient
  3. Most importantly: it works only from API 26 (Android O) , which currently is active on about 1% of Android devices worldwide.

The questions

为什么会这样?

What exactly can I do to make it the most readable, without string conversions, and work on all Android versions (minSdkVersion 14 in my case) ?

推荐答案

Sorry for putting something on such an old question, but an extension function really seemed like the nicest approach:

fun TextView.setTextColor(color: Long) = this.setTextColor(color.toInt())

now, you can just go textView.setTextColor(0xff00ff00) again

Kotlin相关问答推荐

调用即发即忘方法--哪个作用域?

在intellij中使用kotlin符号和floordiv

在Kotlin中,我是否可以访问已知的WHEN子句值?

多模块Kotlin项目中的FreeFair

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

CompositionLocal 究竟如何以及何时隐式设置值?

Kotlin 插件之间的区别

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

在 SplashActivity 中显示的 Firebase 应用内消息.如何在 MainActivity 中显示它?

Kotlin 和 Java 字符串拆分与正则表达式的区别

Android Room - error: Cannot figure out how to save this field into database

在kotlin中,如何模拟封装回调函数?

kotlin RecyclerView分页

Kotlin使用运行时断言进行空判断?

是否在Kotlin中重写enum toString()?

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

如何序列化/反序列化Kotlin密封类?

Kotlin,什么时候按map授权?

var str:String是可变的还是不可变的?

如何在 Kotlin 中按字母顺序对字符串进行排序