在Android上序列化Drawable对象 [英] Serializing a Drawable object on Android

查看:68
本文介绍了在Android上序列化Drawable对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过缓存图像并在滚动列表时从电话而不是从Internet加载图像来加快ListView的速度.但是,当我尝试序列化Drawable对象时遇到了一个异常.这是我的功能:

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();
    }
}

这漂亮的代码导致:

java.io.NotSerializableException:android.graphics.drawable.BitmapDrawable

序列化这些图像的最佳方法是什么?

What is the best approach to serialize these images?

推荐答案

您只需要缓存从互联网上获取的位图(可绘制图片).所有其他可绘制对象很可能在您的apk中.

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.

如果要向文件中写入位图,则可以使用 Bitmap 类:

If you want to write a Bitmap to file you can use the Bitmap class:

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();
    }
}

这篇关于在Android上序列化Drawable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆