看两种方法的源代码,它们似乎非常相似。如果你没有向量,你可能可以随便使用其中的任何一个。
ResourcesCompat.getDrawable()
会在API 21或更高版本上调用Resources#getDrawable(int, theme)
。它还支持Android API 4+。它不过是这样:
public Drawable getDrawable(Resources res, int id, Theme theme)
throws NotFoundException {
final int version = Build.VERSION.SDK_INT;
if (version >= 21) {
return ResourcesCompatApi21.getDrawable(res, id, theme);
} else {
return res.getDrawable(id);
}
}
ResourcesCompatApi21
仅仅调用了 res.getDrawable(id, theme)
。这意味着如果设备不支持矢量图,它将不会允许绘制矢量图形。但是,它仍然允许您传递一个主题。
与此同时,AppCompatResources.getDrawable(Context context, int resId)
的代码更改最终变成了这样:
Drawable getDrawable(@NonNull Context context, @DrawableRes int resId, boolean failIfNotKnown) {
checkVectorDrawableSetup(context);
Drawable drawable = loadDrawableFromDelegates(context, resId);
if (drawable == null) {
drawable = createDrawableIfNeeded(context, resId);
}
if (drawable == null) {
drawable = ContextCompat.getDrawable(context, resId);
}
if (drawable != null) {
// Tint it if needed
drawable = tintDrawable(context, resId, failIfNotKnown, drawable);
}
if (drawable != null) {
// See if we need to 'fix' the drawable
DrawableUtils.fixDrawable(drawable);
}
return drawable;
}
因此,如果可能,它将尝试绘制资源,否则它会查找 ContextCompat
版本以获取资源。然后,如果必要,甚至会对其进行着色。但是,此方法仅支持API 7+。
因此,我猜想你需要决定是否应该使用以下两种方式之一:
您是否需要支持 API 4、5 或 6?
- 是:只能使用
ResourcesCompat
或 ContextCompat
。
- 否:继续到步骤#2。
您是否绝对需要提供自定义主题?
- 是:只能使用
ResourcesCompat
。
- 否:使用
AppCompatResources
AppCompatResources
是唯一一个没有崩溃的吗? - cmak