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

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

我该怎么办?


当前回答

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

例如,获取颜色使用

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

也可以画出来

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

其他回答

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

对于所有的Kotlin用户:

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

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

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

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

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

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