Android获取Drawable对象方式为getResources().getDrawable(@DrawableResId int res), 只可能返回***Drawable、BitmapDrawable对象, 当然id不存在会抛异常。
public abstract class Drawable {
...
}
在/framework/base/graphics/java/android/graphics目录下有很多Drawable派生类。
下面讲解下返回对象是如何产生的, 核心逻辑在ResourcesImpl.java
private final DrawableCache mDrawableCache = new DrawableCache(); //缓存的是ConstantState抽象类的对象,而不是Drawable对象; 弱引用,不影响GC
private final DrawableCache mColorDrawableCache = new DrawableCache(); //弱引用,不影响GC
Drawable loadDrawable(@NonNull Resources wrapper, @NonNull TypedValue value, int id,
int density, @Nullable Resources.Theme theme)
throws NotFoundException {
final boolean useCache = density == 0 || value.density == mMetrics.densityDpi;
//getDrawableForDensity(id, 0, theme);density为0, 所以useCache默认为true,
//app取自己的drawable时mPreloading为false, 即下面的if条件为真
if (!mPreloading && useCache) {
final Drawable cachedDrawable = caches.getInstance(key, wrapper, theme);
if (cachedDrawable != null) {