出身背景
在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:
- 时间要长得多.
- It converts a String, so it's much less efficient
- 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) ?