在 Android 上序列化 Drawable 对象
我试图通过缓存图像并在滚动列表时从手机而不是互联网加载图像来加快 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.NotSerializedException: android.graphics.drawable.BitmapDrawable
序列化这些图像的最佳方法是什么?
I'm trying to speed up my ListView by cacheing the images and loading them from the phone rather than the internet when scrolling the list. However, I run into an exception when I try to serialize the Drawable object. This is my function:
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();
}
}
This nifty bit of code results in:
java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable
What is the best approach to serialize these images?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该只需要缓存从互联网获取的位图(可绘制对象)。所有其他可绘制对象很可能都在您的 apk 中。
如果您想将位图写入文件,可以使用 Bitmap 类:
You should only need to cache bitmap (drawables) that you i.e. fetched from the internet. All other drawables are most likely in your apk.
If you want to write a Bitmap to file you can use the
Bitmap
class:如果您的
Drawables
都是位图,您可以使用 Bitmap.compress()In case your
Drawables
are allBitmaps
you can store them using Bitmap.compress()请参阅 http://code.google.com/p/shelves/ Google Shleves 项目实际上正在做你想做的事。请参阅他们维护对图像的弱引用和软引用的代码。
Please see http://code.google.com/p/shelves/ Google Shleves project they are actually doing what you want. please see code they are maintaining WeakReference and SoftReference to Images.