LruCache 클래스를 이용한 Bitmap 캐쉬 기법
BitmapCacheActivity.java
package com.example.bitmapcache;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.LruCache;
import android.widget.ImageView;
import com.example.test.R;
public class BitmapCacheActivity extends Activity {
private static final String TAG = "BitmapCacheActivity";
private Context mContext = null;
private LruCache<String, Bitmap> mMemoryCache;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_bitmap_cache);
mContext = this;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
String keyImageView = "imageKey";
ImageView iv = (ImageView) findViewById(R.id.imageView);
if (null == getBitmapFromMemCache(keyImageView)) {
iv.setImageBitmap(bitmap);
addBitmapToMemoryCache(keyImageView, bitmap);
} else {
iv.setImageBitmap(getBitmapFromMemCache(keyImageView));
}
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (null == key || null == bitmap) {
return;
}
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
}
|
댓글 없음:
댓글 쓰기