【问题标题】:How to set color using integer?如何使用整数设置颜色?
【发布时间】:2012-01-19 08:55:57
【问题描述】:

如何将整数 ex: 13369395 中的颜色代码转换为特定于 android 的颜色代码。由于 13369395 也是我尝试做的整数

mainLayout.setTextColor(13369395);

但它不起作用。

我还尝试将 13369395 转换为十六进制,例如:

mainLayout.setBackgroundColor(Integer.parseInt(13369395 +"", 16)+0xFF000000);

但它也没有帮助。

【问题讨论】:

    标签: android-layout colors views setbackground


    【解决方案1】:

    可以直接取16进制码。例如

    mainLayout.setBackgroundColor(#0BB5FF);

    【讨论】:

    • 我得到了解决方案。只需使用 Hexadecimal 即可,如下所示: Integer.toHexString(colour);它返回整数的十六进制字符串,如果你只是通过 mainLayout.setBackgroundColor(Integer.parseInt(hexVal,16));它不会工作。您需要将掩码添加为 mainLayout.setBackgroundColor(0xff000000 + Integer.parseInt(hexVal,16));这解决了这个问题。谢谢
    • mainLayout.setBackgroundColor(#0BB5FF);从 Java 1.6 开始不支持此功能
    【解决方案2】:

    我得到了解决方案。只需使用 Hexadecimal 即可,如下所示:

    Integer.toHexString(colour);

    返回整数的十六进制字符串,如果你只是使用它

    mainLayout.setBackgroundColor(Integer.parseInt(hexVal,16));

    它不会工作。您需要将掩码添加为

    mainLayout.setBackgroundColor(0xff000000 + Integer.parseInt(hexVal,16));

    这已经解决了问题

    【讨论】:

      【解决方案3】:

      这个问题很老了。这个答案仍然可以帮助那些寻找将颜色直接设置为整数的方法的人。

      如果您查看 android 文档,白色的常量值为 -1,黑色为 -16777216。 (即)整个颜色 int 值范围是(-1 到 -16777216)。所以你可以简单地将整数值添加到 -16777216。

      例如,如果你想设置十进制表示为 16777215 (0xffffff) 的白色,那么 16777215 - 16777216 会给你 -1 在 android 中黑色的颜色常数。

      【讨论】:

        【解决方案4】:

        尝试通过:

        mainLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
        

        【讨论】:

          猜你喜欢
          • 2021-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多