android - 如何在 Kotlin for Android 上使用 "setTextColor(hexaValue)",

标签 android textview kotlin

背景

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

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

非常简单...

问题

在 Kotlin 上,如果我尝试编写这样的东西,我会遇到一个奇怪的构建错误:

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

我尝试过的

我试图在 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

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

我唯一能想到的,仍然可以很好地阅读它,是这样的:

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

但是,这有多个缺点:

  1. 它更长。
  2. 它转换的是字符串,所以效率很低
  3. 最重要的是:它仅适用于 API 26 (Android O),该 API 目前在全局约 1% 的 Android 设备上有效。

问题

为什么会发生?

我究竟该怎么做才能使其最易读,无需字符串转换,并适用于所有 Android 版本(在我的例子中为 minSdkVersion 14)?

最佳答案

textView.setTextColor(Color.parseColor("#0aad3f"))

关于android - 如何在 Kotlin for Android 上使用 "setTextColor(hexaValue)",,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001467/

相关文章:

android - 在 Android 上监听通知

java - 将库构建为jar文件

android - 加载 flutter 时去除图像中的白色闪烁

android - 如何使用 Paging 3 处理大量 Api 请求

android - ViewModel 将 ArrayList 大小返回为零

java - 适用于 Android 的 Google+ java 入门应用程序出现黑屏?

android - DisplayMessageActivity.java 上的 MyFirstApp android 教程错误

android - 使用多行跳转到某行 EditText 或 TextView

android - 如何将带有高亮颜色背景的文本添加到 ImageView

java - Android 语音识别器自动停止 - 需要像 Google Bolo App 一样实现