资源。getColor(int id)方法已弃用。

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

我该怎么办?


当前回答

对于所有的Kotlin用户:

context?.let {
    val color = ContextCompat.getColor(it, R.color.colorPrimary)
    // ...
}

其他回答

最好的等效方法是使用ContextCompat。getColor和ResourcesCompat。色鬼。我做了一些扩展函数用于快速迁移:

@ColorInt
fun Context.getColorCompat(@ColorRes colorRes: Int) = ContextCompat.getColor(this, colorRes)

@ColorInt
fun Fragment.getColorCompat(@ColorRes colorRes: Int) = activity!!.getColorCompat(colorRes)

@ColorInt
fun Resources.getColorCompat(@ColorRes colorRes: Int) = ResourcesCompat.getColor(this, colorRes, null)

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的官方参考

tl; diana:

ContextCompat.getColor(context, R.color.my_color)

解释:

您将需要使用ContextCompat.getColor(),它是Support V4库的一部分(它将适用于前面的所有api)。

ContextCompat.getColor(context, R.color.my_color)

如果你还没有使用支持库,你将需要添加以下一行到你的应用程序构建中的依赖数组。gradle(注意:如果你已经使用了appcompat (V7)库,它是可选的):

compile 'com.android.support:support-v4:23.0.0' # or any version above

如果你关心主题,文档指定:

从M开始,返回的颜色将为指定的样式 上下文的主题

我也很沮丧。我的需求非常直截了当。我想要的只是资源中的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;
}

在Kotlin中,你可以这样做:

ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)

如果requireContext()可以从调用函数的地方访问。我在尝试时得到一个错误

ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)