我试图通过缓存图像来加速我的ListView,并在滚动列表时从手机而不是互联网加载它们。但是,当我尝试序列化Drawable对象时,我遇到了异常。这是我的功能:
private void cacheImage(Drawable dr, Article a){
FileOutputStream fos;
try {
fos = openFileOutput(a.getArticleId().toString(), Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dr);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
这段漂亮的代码导致:
java.io.NotSerializableException:android.graphics.drawable.BitmapDrawable
序列化这些图像的最佳方法是什么?
答案 0 :(得分:6)
您应该只需要缓存您从互联网上获取的位图(drawables)。所有其他drawables最有可能在你的apk中。
如果要将Bitmap写入文件,可以使用Bitmap
类:
private void cacheImage(BitmapDrawable dr, Article a){
FileOutputStream fos;
try {
fos = openFileOutput(a.getArticleId().toString(), Context.MODE_PRIVATE);
dr.getBitmap().compress(Bitmap.CompressFormat.PNG, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
答案 1 :(得分:0)
如果您的Drawables
全部为Bitmaps
,则可以使用Bitmap.compress()
答案 2 :(得分:-2)
请参阅http://code.google.com/p/shelves/ Google Shelves项目,他们实际上正在做您想做的事情。请参阅代码,他们正在维护弱参考和图像的软参考。