从 rgb Stringin Java 创建颜色

Create Color from rgb Stringin Java

这是我将字符串转换为颜色的代码:

public Color prepareColour(String str) {
    str.replace("#", "");
    float r = Float.valueOf(str.substring(0,1));
    float g = Float.valueOf(str.substring(2,3));
    float b = Float.valueOf(str.substring(4,5));
    Color color = Color.valueOf(r,g,b);
    return color;

}

我收到以下调试错误:

Error:(16, 23) error: constructor Color in class Color cannot be applied to given types; required: no arguments found: float,float,float reason: actual and formal argument lists differ in length

但是,从Android Studio编译之前的建议是:

Call requires API level 26 (current min is 17) ......

我看到 2011 年的答案支持这种创建颜色的方式,所以它肯定适用于 API 17 而不需要 26。

我已经尝试清理和重建项目,并用实际值替换 str.substring,但没有任何变化。

为什么代码无法编译?

您是否尝试过使用 Color.rgb(r,g,b) 而不是 Color.valueOf(...)Color.valueOf(...) 是 Android Developer O 预览版中的一个非常新的方法,因此目前只能在 1 API 级别上使用。

此外,请确保您使用的是 0-255 范围内的整数,或 0-1 范围内的浮点数。

您可以使用此代码。

Color.parseColor(String strColor);

这是Colorclass

的静态方法
public static int parseColor (String colorString)

https://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String)