过时的getResources().getColor,和getResources().getDrawable

来源:互联网 发布:淘宝仓库招聘要求 编辑:程序博客网 时间:2024/05/29 17:11

解决方案:
利用ContextCompat中的方法
ContextCompat.getColor(getContext(),R.color.main_background);
ContextCompat.getDrawable(getContext(),R.drawable.ic_launcher);

源码为:

@ColorInt
public static final int getColor(Context context, @ColorRes int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 23) {
return ContextCompatApi23.getColor(context, id);
} else {
return context.getResources().getColor(id);
}
}

public static final Drawable getDrawable(Context context, @DrawableRes int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 21) {
return ContextCompatApi21.getDrawable(context, id);
} else if (version >= 16) {
return context.getResources().getDrawable(id);
} else {
// Prior to JELLY_BEAN, Resources.getDrawable() would not correctly
// retrieve the final configuration density when the resource ID
// is a reference another Drawable resource. As a workaround, try
// to resolve the drawable reference manually.
final int resolvedId;
synchronized (sLock) {
if (sTempValue == null) {
sTempValue = new TypedValue();
}
context.getResources().getValue(id, sTempValue, true);
resolvedId = sTempValue.resourceId;
}
return context.getResources().getDrawable(resolvedId);
}
}

0 0
原创粉丝点击