private final Map<Key, Bitmap> 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) {
returntrue;
}
if (o == null || getClass() != o.getClass()) {
returnfalse;
}
Key key = (Key) o;
if (width != key.width) {
returnfalse;
}
if (heifht != key.heifht) {
returnfalse;
}
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; } 複製代碼