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