实现LruCache

时间:2014-08-24 22:34:39

标签: android-lru-cache

我正在尝试将Lru Cache实现到我的程序中,以使我的listview滚动更快。我不确定在addBitmapToCache的Bitmap值中放置什么(String键,Bitmap位图(由XXXXXX表示)。有人有建议吗?谢谢。

public class ImageCache extends LruCache<String, Bitmap> {

public ImageCache(int maxSize) {
    super(maxSize);
}

@Override
protected int sizeOf(String key, Bitmap value) {
    return value.getByteCount() / 1024;
}

public void addBitmapToCache(String key, Bitmap bitmap) {
    if (getBitmapFromCache(key) == null) {
        put(key, bitmap);
    }
}

public Bitmap getBitmapFromCache(String key) {
    return get(key);
}
}

这是我实施它的地方。

@Override
public View getView(int position, View convertView, ViewGroup parent)
{

    ViewHolder holder;
    View rowView = convertView;

    if(rowView==null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.listview_layout, parent, false);
        holder = new ViewHolder();
        holder.img = (ImageView) rowView.findViewById(R.id.flag);
        rowView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) rowView.getTag();
    }
    //holder.img.setImageResource(imageIds.get(position));

    loadBitmap(imageIds.get(position),holder.img);
    return rowView;
}

public void loadBitmap(int resId, ImageView imageView) {
    final String imageKey = String.valueOf(resId);
    Bitmap storeBitmap;
    final Bitmap bitmap = mCache.getBitmapFromCache(imageKey);
    if (bitmap != null) {
        imageView.setImageBitmap(bitmap);
    } else {
        imageView.setImageResource(resId);
        storeBitmap = BitmapFactory.decodeResource(imageView.getResources(), resId);
        mCache.addBitmapToCache(String.valueOf(resId), storeBitmap);
    }
}

1 个答案:

答案 0 :(得分:0)

调用BitmapFactory.decodeResource(imageView.getResources(), resId)从资源加载位图并将其放入图像缓存中。下次你需要它时,它将出现在缓存中,这将加快列表项视图的设置。