在Android 6.0 Marshmallow (API 23)中,getColor(int id)已经被弃用。

788

Resources.getColor(int id)方法已被弃用。

@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
    return getColor(id, null);
}

我该怎么办?


38
使用ContextCompat.getColor(context, R.color.color_name)获取颜色。 - Ashokchakravarthi Nagarajan
通过上面提到的方法:getColor(context, R.color.your_color); 不清楚如何获取“context”。在我的情况下,仅仅把context放在那里是行不通的,因为我使用的是Android Studio 3.2。我发现这对我有用:.setTextColor(Color.RED)。 - Harry
14个回答

1
使用 Android 支持库中的 ResourcesCompatgetColor(Resources, int, Theme) 方法。
int white = ResourcesCompat.getColor(getResources(), R.color.white, null);

我认为相对于ContextCompat中的getColor(Context, int),这更好地反映了您关于Resources的问题。在API级别23之前,主题不会被应用,方法调用会通过getColor(int)进行,但您将不会收到已弃用的警告。主题也可能是null

1
如果您将主题参数设置为 null,则返回的颜色将不会针对当前主题进行样式化,因此可能是不正确的。 - araks
@araks 不过这不是和已弃用的调用一样吗?毕竟,在两种情况下,您都会获得资源实例,而不是上下文。 - android developer
@androiddeveloper 他们正是因为这个原因而弃用了该调用:为了避免加载非主题资源。如果您传递null,则会使所有代码迁移的努力无效,以修复此弃用,并使自己面临加载非主题资源(主要是可绘制对象)的风险,而没有任何明确的指示说明它们未按预期工作的原因。因此,您应始终从当前Activity / Fragment提供Theme实例或使用ContextCompat.get *方法。 - araks
@araks 你是指drawables中使用"?attr/"的情况吗? - android developer

1
如果不需要资源,可以使用 parseColor(String) 函数:
Color.parseColor("#cc0066")

0

我也感到沮丧。我的需求非常简单。我只想从资源中获取ARGB颜色,所以我编写了一个简单的静态方法。

protected static int getARGBColor(Context c, int resId)
        throws Resources.NotFoundException {

    TypedValue color = new TypedValue();
    try {
        c.getResources().getValue(resId, color, true);
    }
    catch (Resources.NotFoundException e) {
        throw(new Resources.NotFoundException(
                  String.format("Failed to find color for resourse id 0x%08x",
                                resId)));
    }
    if (color.type != TYPE_INT_COLOR_ARGB8) {
        throw(new Resources.NotFoundException(
                  String.format(
                      "Resourse id 0x%08x is of type 0x%02d. Expected TYPE_INT_COLOR_ARGB8",
                      resId, color.type))
        );
    }
    return color.data;
}

0

getColor(int): 这个方法在API 23级中已经被弃用。 请使用getColor(int, android.content.res.Resources.Theme)代替。

我尝试了minSDK = 21:

if(Build.VERSION.SDK_INT < 23) {
                resources.getColor(R.color.rippelColor, null)
            } else {
                resources.getColor(R.color.rippelColor)
            }

来自developer.android.com的官方参考资料


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接