getColor(int id) 在 Android 6.0 Marshmallow (API 23) 上弃用

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

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

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

我该怎么办?

从 Android 支持库 23 开始,
新的 getColor() 方法已添加到 ContextCompat

来自官方JavaDoc的描述:

Returns a color associated with a particular resource ID

Starting in M, the returned color will be styled for the specified Context's theme.


所以,只需调用:

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

您可以查看 ContextCompat.getColor() source code on GitHub.

tl;博士:

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

解释:

您将需要使用 ContextCompat.getColor(),它是支持 V4 库的一部分(它将适用于所有以前的 API)。

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

如果您还没有使用支持库,则需要将以下行添加到您的应用 dependencies 数组中 build.gradle(注意:它是可选的如果您已经使用了 appcompat (V7) 库):

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

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

Starting in M, the returned color will be styled for the specified Context's theme

在 Android Marshmallow 中许多方法已被弃用。

例如,要获取颜色,请使用

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

也可用于绘制

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

我不想只为 getColor 添加支持库,所以我使用了类似

的东西
public static int getColorWrapper(Context context, int id) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return context.getColor(id);
    } else {
        //noinspection deprecation
        return context.getResources().getColor(id);
    }
}

我想代码应该可以正常工作,并且已弃用的 getColor 不会从 API < 23.

中消失

这就是我在 Kotlin 中使用的:

/**
 * Returns a color associated with a particular resource ID.
 *
 * Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
 */
@Suppress("DEPRECATION")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
    if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);

使用 Android 支持库中 ResourcesCompatgetColor(Resources, int, Theme) 方法。

int white = ResourcesCompat.getColor(getResources(), R.color.white, null);

我认为它比 ContextCompatgetColor(Context, int) 更能反映你的问题,因为你问的是 Resources。在 API 级别 23 之前,不会应用主题并且方法会调用 getColor(int) 但您不会收到已弃用的警告。主题也可以是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;
}

如果您不一定需要这些资源,请使用 parseColor(String)
Color.parseColor("#cc0066")

致所有 Kotlin 用户:

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

在 Kotlin 中的 RecyclerView 中

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
        textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
        textViewcolor.text = t.name
    }
}

如果您的 当前最低。 API 级别是 23,你可以简单地使用 getColor() 就像我们通过 getString():

获取字符串资源一样
//example
textView.setTextColor(getColor(R.color.green));
// if `Context` is not available, use with context.getColor()

您可以限制 API 低于 23 的级别:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    textView.setTextColor(getColor(R.color.green));
} else {
    textView.setTextColor(getResources().getColor(R.color.green));
}

但为了简单起见,您可以像下面那样接受答案:

textView.setTextColor(ContextCompat.getColor(context, R.color.green))

来自 Resources.

来自 ContextCompat AndroidX.

来自ContextCompat Support

在 Kotlin 中,您可以:

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

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

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

最好的等效方法是使用 ContextCompat.getColorResourcesCompat.getColor 。为了快速迁移,我做了一些扩展功能:

@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)

在 activity 中使用了 ContextCompat

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

在阿达珀

private Context context;


context.getResources().getColor()