在Android中缓存图像有意义吗?



RecyclerView.Adapter onBindViewHolder现在是这样的:

@Override
public void onBindViewHolder(UserSettingHolder userSettingHolder, int i) {
   // .. some code
    try {
        // TODO: Image loader need
        File file = new File(MainActivity.context.getFilesDir(), _id + ".photo");
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[(int) file.length()];
        int numRead = in.read(buf);
        Bitmap bitmap = BitmapFactory.decodeByteArray(buf, 0, numRead);
        userSettingHolder.icon.setImageBitmap(bitmap);
    } catch (Exception e) {
        System.out.print(e);
    }
} 

我猜总是从文件系统中读取文件是不有效的,特别是在onBindViewHolder中,它经常被调用。你会建议使用"内存缓存"来存储图像吗?在iOS中,NSCache是为此提供的。NSCache有一个优势,如果你用完内存,它将首先被清除。

Android的替代技术是什么?

有很多第三方库可以用于这种情况。下面是一个使用glide的例子:

     Glide.with(context)
    .load(filePath)
    .setMemoryCache(new LruResourceCache(yourSizeInBytes))
    .into(youImageView);

Lib: https://github.com/bumptech/glide

最新更新