private final Map cache = new HashMap<>();private void setImage(ImageView iv, String name, int width, int height){ Key key = new Key(name, width, height); Bitmap b = cache.get(key); if(b == null){ b = loadBitmap(name, width, height); cache.put(key, b); } iv.setImageBitmap(b);}public class Key { private final String name; private final int width; private final int heifht; public Key(String name, int width, int heifht) { this.name = name; this.width = width; this.heifht = heifht; } public String getName() { return name; } public int getWidth() { return width; } public int getHeifht() { return heifht; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Key key = (Key) o; if (width != key.width) { return false; } if (heifht != key.heifht) { return false; } return name != null ? name.equals(key.name) : key.name == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; final int prime = 31; result = prime * result + width; result = prime * result + heifht; return result; }}复制代码
strategy 是 LruPoolStrategy 接口类型,查看其中一个继承该接口类的 get 方法的实现
@Override @NonNull public Bitmap get(int width, int height, Bitmap.Config config) { Bitmap result = getDirtyOrNull(width, height, config); if (result != null) { // Bitmaps in the pool contain random data that in some cases must be cleared for an image // to be rendered correctly. we shouldn't force all consumers to independently erase the // contents individually, so we do so here. See issue #131. result.eraseColor(Color.TRANSPARENT); } else { result = createBitmap(width, height, config); } return result; } @Nullable private synchronized Bitmap getDirtyOrNull( int width, int height, @Nullable Bitmap.Config config) { assertNotHardwareConfig(config); // 对于非公共配置类型,配置为NULL,这可能导致转换以此处请求的配置方式天真地传入NULL。 final Bitmap result = strategy.get(width, height, config != null ? config : DEFAULT_CONFIG); if (result == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Missing bitmap=" + strategy.logBitmap(width, height, config)); } misses++; } else { hits++; currentSize -= strategy.getSize(result); tracker.remove(result); normalize(result); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Get bitmap=" + strategy.logBitmap(width, height, config)); } dump(); return result; }复制代码