资源。getColor(int id)方法已弃用。
@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
return getColor(id, null);
}
我该怎么办?
资源。getColor(int id)方法已弃用。
@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
return getColor(id, null);
}
我该怎么办?
当前回答
在活动中使用ContextCompat
ContextCompat.getColor(context, R.color.color_name)
在改编电影
private Context context;
context.getResources().getColor()
其他回答
从Android支持库23开始, ContextCompat中添加了一个新的getColor()方法。
它在官方JavaDoc中的描述:
返回与特定资源ID相关联的颜色 从M开始,返回的颜色将为指定上下文的主题设置样式。
所以,只需调用:
ContextCompat.getColor(context, R.color.your_color);
你可以在GitHub上查看ContextCompat.getColor()源代码。
我不想仅为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);
在活动中使用ContextCompat
ContextCompat.getColor(context, R.color.color_name)
在改编电影
private Context context;
context.getResources().getColor()
使用Android支持库中的ResourcesCompat的getColor(Resources, int, Theme)方法。
int white = ResourcesCompat.getColor(getResources(), R.color.white, null);
我认为它比ContextCompat的getColor(Context, int)更好地反映了您的问题,因为您询问了资源。在API级别23之前,主题将不会被应用,方法将调用getColor(int),但您将不会看到已弃用的警告。主题也可以为空。
在Android Marshmallow中,许多方法都被弃用了。
例如,获取颜色使用
ContextCompat.getColor(context, R.color.color_name);
也可以画出来
ContextCompat.getDrawable(context, R.drawable.drawble_name);