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

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

我该怎么办?


当前回答

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

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

在Kotlin中,你可以这样做:

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

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

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

在活动中使用ContextCompat

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

在改编电影

private Context context;


context.getResources().getColor()

在Android Marshmallow中,许多方法都被弃用了。

例如,获取颜色使用

ContextCompat.getColor(context, R.color.color_name);

也可以画出来

ContextCompat.getDrawable(context, R.drawable.drawble_name);

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