资源。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)
    // ...
}

其他回答

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

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

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

我认为它比ContextCompat的getColor(Context, int)更好地反映了您的问题,因为您询问了资源。在API级别23之前,主题将不会被应用,方法将调用getColor(int),但您将不会看到已弃用的警告。主题也可以为空。

从Android支持库23开始, ContextCompat中添加了一个新的getColor()方法。

它在官方JavaDoc中的描述:

返回与特定资源ID相关联的颜色 从M开始,返回的颜色将为指定上下文的主题设置样式。


所以,只需调用:

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

你可以在GitHub上查看ContextCompat.getColor()源代码。

在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
    }
}

如果你不需要这些资源,使用parseColor(String): Color.parseColor(“# cc0066”)