在Java中,我可以使用它的标准十六进制值直接更改TextView的文本颜色:
textView.setTextColor(0xffffffff); //white
textView.setTextColor(0x00000000); //transparent
textView.setTextColor(0xff000000); //black
textView.setTextColor(0xff0000ff); //blue
//etc...
Run Code Online (Sandbox Code Playgroud)
很容易...
在Kotlin上,如果我尝试编写这样的东西,则会遇到奇怪的构建错误:
错误:(15,18)使用提供的参数无法调用以下函数:public open fun setTextColor(p0:ColorStateList!):android.widget.TextView中定义的单元public open fun setTextColor(p0:Int):单位在android.widget.TextView中定义
我尝试通过Internet搜索此内容,但没有看到关于十六进制值的任何特殊信息。好像在Java上一样:
https://kotlinlang.org/docs/reference/basic-types.html
然后我决定只用Java编写,然后转换为Kotlin。就颜色值而言,结果非常不可读:
textView.setTextColor(-0x1) //white
textView.setTextColor(0x00000000) //transparent
textView.setTextColor(-0x1000000) //black
textView.setTextColor(-0xffff01) //blue
Run Code Online (Sandbox Code Playgroud)
在我看来,用于Kotlin的Integer的十六进制值是带符号的,而在Java上,它会自动转换为带符号的十六进制,因此这会导致值翻转,并且需要在需要时设置减号。
我唯一能想到的仍然是这样的东西:
textView.setTextColor(Integer.parseUnsignedInt("ffff0000",16));
Run Code Online (Sandbox Code Playgroud)
但是,这有多个缺点:
为什么会发生?
我该如何做才能使其在不进行字符串转换的情况下最易读,并且可以在所有Android版本上使用(在我的情况下为minSdkVersion 14)?
我有一个 32 位十六进制值,我希望将其转换为整数。
给定十六进制字符串,以下方法都提供以下错误C71C5E00
:
java.lang.NumberFormatException:对于输入字符串:“C71C5E00”
"C71C5E00".toInt(32)
Integer.valueOf("C71C5E00", 32)
Run Code Online (Sandbox Code Playgroud)
Kotlin文档指出 Int表示 32 位有符号整数,因此并不是说该值太大而无法装入 Int。我试过,在0x
字符串之前,徒劳无功。
编辑:根据这个问题,我尝试过:
java.lang.Integer.parseInt("C71C5E00", 32)
Run Code Online (Sandbox Code Playgroud)
不幸的是,我仍然收到同样的错误。
我不经常接触 Android 或 Kotlin,所以请原谅我的无知。