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

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

我该怎么办?


当前回答

在Kotlin中,你可以这样做:

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

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

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

其他回答

对于所有的Kotlin用户:

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

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

最好的等效方法是使用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的官方参考

如果你当前的最小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))

从资源。

来自ContextCompat AndroidX。

来自ContextCompat Support