Android LruCache不使用imageAdapter

Android LruCache不使用imageAdapter,android,bitmap,android-lru-cache,Android,Bitmap,Android Lru Cache,我的资源中有11张图片。我使用GridView来显示它们 因为图像在我的ImageAdapter类中占用了大量空间,所以我计算样本大小,然后根据教程对资源进行解码,以有效地加载图像 在从decodeSampledBitmapFromResource返回解码后的位图之前,我要将位图添加到LruCache: Bitmap b = BitmapFactory.decodeResource(res, resId, options); String key = Integer.toStri

我的资源中有11张图片。我使用GridView来显示它们

因为图像在我的ImageAdapter类中占用了大量空间,所以我计算样本大小,然后根据教程对资源进行解码,以有效地加载图像

在从
decodeSampledBitmapFromResource
返回解码后的位图之前,我要将位图添加到LruCache:

    Bitmap b = BitmapFactory.decodeResource(res, resId, options);
    String key = Integer.toString(resId);   
   // Log.i("byte", "b.getByteCount()=="  + b.getByteCount());
    addBitmapToMemoryCache(key, b);         //add to cache
这会导致我的
getView()
尝试获取缓存的位图,如果它不是空的-否则使用我上面提到的方法

要从缓存中添加和获取位图,我正在使用:

    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        Log.i("addbitmaptocache", "Add key= " + key);
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
        Log.i("getbitmaptocache", "GET KEY= " + key);
        return mMemoryCache.get(key);
}
发生的事情是,
if(cachedBitmap!=null)
从来都不是真的,这让我相信出了问题

该类的完整代码:

public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int wid;

private static final String AdapterTAG="adapterTAG";

// private ImageView imageView;
private Bitmap mBitmap;
private LruCache<String, Bitmap> mMemoryCache;


public ImageAdapter(Context c, int wid) {
    mContext = c;
    this.wid = wid;
}

public int getCount() {
    return mThumbIds.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolderItem viewHolder;
     int new_width = wid/2;

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.grid_item, parent, false);

        // well set up the ViewHolder
        viewHolder = new ViewHolderItem();
        viewHolder.textViewItem = (TextView) convertView.findViewById(R.id.textId);
        viewHolder.imageViewItem = (ImageView) convertView.findViewById(R.id.imageId);

        // store the holder with the view.
        convertView.setTag(viewHolder);

       } else{
            viewHolder = (ViewHolderItem) convertView.getTag();
        }

    /**   ********************  Caching  ******************** **/
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
//  Log.i("max", "maxMemory== " + maxMemory );

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 4;
   // Log.i("cachesize", "cachesize== " + cacheSize);

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getByteCount() / 1024;
        }
    };

    //Log.i("mMemoryCache", "mMemoryCache= " + mMemoryCache);

    viewHolder.textViewItem.setId(position); 

    viewHolder.imageViewItem.getLayoutParams().width = new_width -5;
    viewHolder.imageViewItem.getLayoutParams().height = new_width -5;

    viewHolder.imageViewItem.setScaleType(ImageView.ScaleType.CENTER_CROP);
    viewHolder.imageViewItem.setPadding(0, 0, 0, 0);


    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = false;


    final String imageKey = String.valueOf(mThumbIds[position]);         
    final Bitmap cachedBitmap = getBitmapFromMemCache(imageKey);            // use cached Bitmap or ... decode
    if ( cachedBitmap != null ) {
        Log.i("cached", "CACHED BITMAP FOR THE WIN!!!!");
        viewHolder.imageViewItem.setImageBitmap(cachedBitmap);
    } else {
        viewHolder.imageViewItem.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(), mThumbIds[position]  , new_width, 200));
    }

    return convertView;
}

static class ViewHolderItem {
    TextView textViewItem;
    ImageView imageViewItem;
}



// references to our images
private Integer[] mThumbIds = {
        R.drawable.wallpaper0, R.drawable.wallpaper1,
        R.drawable.wallpaper2, R.drawable.wallpaper3,
        R.drawable.wallpaper4, R.drawable.wallpaper5,
        R.drawable.wallpaper6, R.drawable.wallpaper7,
        R.drawable.wallpaper8, R.drawable.wallpaper9,
        R.drawable.wallpaper10
};


public  Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    //  Log.i("req", "reqWidth=  " + reqWidth + " reqHeight=" + reqHeight );  // params

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;
    String imageType = options.outMimeType;

    Log.i("options", "Width== " + imageWidth  + " Height== "  + imageHeight + " Type== "  + imageType );

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inPurgeable = true; 
    options.inInputShareable = true;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    Bitmap b = BitmapFactory.decodeResource(res, resId, options);
    String key = Integer.toString(resId);   
   // Log.i("byte", "b.getByteCount()=="  + b.getByteCount());
    addBitmapToMemoryCache(key, b);         //add to cache

    return b;
}    



public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    Log.i("sample", "size=" +inSampleSize );
    return inSampleSize;
}    



public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        Log.i("addbitmaptocache", "Add key= " + key);
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
        Log.i("getbitmaptocache", "GET KEY= " + key);
        return mMemoryCache.get(key);
}
公共类ImageAdapter扩展了BaseAdapter{
私有上下文;
私人int wid;
私有静态最终字符串AdapterTAG=“AdapterTAG”;
//私人影像视图;
私有位图mBitmap;
私人LruCache-mMemoryCache;
公共图像适配器(上下文c,int-wid){
mContext=c;
this.wid=wid;
}
public int getCount(){
返回mThumbIds.length;
}
公共对象getItem(int位置){
返回null;
}
公共长getItemId(int位置){
返回0;
}
//为适配器引用的每个项目创建新的ImageView
公共视图getView(int位置、视图转换视图、视图组父视图){
视窗支架视窗支架;
int new_width=wid/2;
if(convertView==null){
LayoutInflater充气器=(LayoutInflater)mContext.getSystemService(Context.LAYOUT\u充气器\u服务);
convertView=充气机。充气(R.layout.grid_项,父项,false);
//很好地设置了取景器
viewHolder=新的ViewHolderItem();
viewHolder.textViewItem=(TextView)convertView.findViewById(R.id.textId);
viewHolder.imageViewItem=(ImageView)convertView.findViewById(R.id.imageId);
//将支架与视图一起存放。
convertView.setTag(viewHolder);
}否则{
viewHolder=(ViewHolderItem)convertView.getTag();
}
/***************************缓存*************************************/
final int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);
//Log.i(“max”,“maxMemory==”+maxMemory);
//将可用内存的1/8用于此内存缓存。
最终int cacheSize=maxMemory/4;
//Log.i(“cachesize”,“cachesize==”+cachesize);
mMemoryCache=新的LruCache(缓存大小){
@凌驾
受保护的int-sizeOf(字符串键、位图){
返回bitmap.getByteCount()/1024;
}
};
//Log.i(“mMemoryCache”,“mMemoryCache=“+mMemoryCache”);
viewHolder.textViewItem.setId(位置);
viewHolder.imageViewItem.getLayoutParams().width=new_width-5;
viewHolder.imageViewItem.getLayoutParams().height=new_width-5;
viewHolder.imageViewItem.setScaleType(ImageView.ScaleType.CENTER\U裁剪);
viewHolder.imageViewItem.setPadding(0,0,0,0);
BitmapFactory.Options=new-BitmapFactory.Options();
options.inJustDecodeBounds=false;
最终字符串imageKey=String.valueOf(mThumbIds[position]);
最终位图cachedBitmap=getBitmapFromMemCache(imageKey);//使用缓存的位图或…解码
if(cachedBitmap!=null){
Log.i(“缓存”,“缓存位图用于赢取!!!!”);
viewHolder.imageViewItem.setImageBitmap(cachedBitmap);
}否则{
viewHolder.imageViewItem.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(),mThumbIds[position],new_width,200));
}
返回视图;
}
静态类ViewHolderItem{
TextView textViewItem;
ImageView imageViewItem;
}
//参考我们的图像
私有整数[]mThumbIds={
R.drawable.Wallper0,R.drawable.Wallper1,
R.drawable.Wallper2,R.drawable.Wallper3,
R.drawable.wallper4,R.drawable.wallper5,
R.drawable.Wallper6,R.drawable.Wallper7,
R.drawable.Wallper8,R.drawable.Wallper9,
R.drawable.10壁纸
};
公共位图解码SampledBitMapFromResource,
输入要求宽度,输入要求高度){
//Log.i(“req”,“reqWidth=“+reqWidth+”reqHeight=“+reqHeight”);//参数
//使用INJUSTDECBOUNDS首次解码=true检查尺寸
final BitmapFactory.Options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;
解码资源(res、resId、options);
int imageHeight=options.outHeight;
int imageWidth=options.outWidth;
字符串imageType=options.outMimeType;
Log.i(“选项”,“宽度=”+imageWidth+“高度=”+imageHeight+“类型=”+imageType”);
//计算样本大小
options.inSampleSize=计算样本大小(options、reqWidth、reqHeight);
options.inpurgable=true;
options.inInputShareable=true;
//使用inSampleSize集合解码位图
options.inJustDecodeBounds=false;
位图b=BitmapFactory.decodeResource(res、resId、options);
字符串key=Integer.toString(resId);
//Log.i(“字节”,“b.getByteCount()=”+b.getByteCount());
addBitMaptomeryCache(键,b);//添加到缓存
返回b;
}    
公共静态int-calculateInSampleSize(BitmapFactory.Options选项、int-reqWidth、int-reqHeight){
//图像的原始高度和宽度
最终内部高度=options.outHeight;
最终整数宽度=options.outWidth;
int inSampleSize=1;
如果(高度>要求高度| |宽度>要求宽度){
最终int半高=高度/2;
最终整数半宽度=宽度/2;
//计算最大的inSampleSize值,该值为2的幂次方,并同时保持这两个值
//高度和宽度大于请求的高度和宽度。
而((半高/采样)大于所需高度
&&(半宽/采样尺寸)>reqWidth){
inSampleSize*=2;
}
}
Log.i(“样本”,“大小=”