You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将十六进制颜色字符串转换为Int类型颜色值?

如何将带0xFF前缀的十六进制颜色字符串转换为Int型颜色值?

我想要为View设置渐变背景,编写了如下代码:

val startColor = "0xFFAC235E"
val endColor = "0xFF640C35"
val gradient = GradientDrawable(
    GradientDrawable.Orientation.LEFT_RIGHT,
    intArrayOf(
        startColor.toInt(),
        endColor.toInt()
    )
)
view.background = gradient

但运行时抛出异常:

java.lang.NumberFormatException: For input string: "0xFFAC235E"

直接使用0xFFAC235E这类Int型颜色值时代码可正常运行,但我需要以字符串形式传入颜色参数,请问该如何实现转换?


问题根源

String.toInt()默认按十进制解析字符串,而"0xFFAC235E"是十六进制格式的字符串,直接调用会触发解析异常。

两种可行的转换方案

  • 方案1:使用Integer.decode()自动解析
    该方法支持识别带0x、0X或#前缀的十六进制字符串,直接完成转换:

    val startColor = "0xFFAC235E"
    val endColor = "0xFF640C35"
    val gradient = GradientDrawable(
        GradientDrawable.Orientation.LEFT_RIGHT,
        intArrayOf(
            Integer.decode(startColor),
            Integer.decode(endColor)
        )
    )
    view.background = gradient
    
  • 方案2:手动处理前缀后按十六进制解析
    先移除字符串中的0x/0X前缀,再调用toInt(16)指定十六进制基数:

    val startColor = "0xFFAC235E"
    val endColor = "0xFF640C35"
    
    // 自定义转换函数
    fun hexColorToInt(hexStr: String): Int {
        return hexStr.removePrefix("0x").removePrefix("0X").toInt(16)
    }
    
    val gradient = GradientDrawable(
        GradientDrawable.Orientation.LEFT_RIGHT,
        intArrayOf(
            hexColorToInt(startColor),
            hexColorToInt(endColor)
        )
    )
    view.background = gradient
    

补充说明

如果你的颜色字符串是Android常用的#FFAC235E格式,上述两种方案同样适用,无需额外调整。


内容的提问来源于stack exchange,提问作者ninhnau19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 13:50:23