【问题标题】:Serializing a Drawable object on Android在 Android 上序列化 Drawable 对象
【发布时间】:2011-10-05 06:28:37
【问题描述】:

我正在尝试通过缓存图像并在滚动列表时从手机而不是互联网加载它们来加速我的 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

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

【问题讨论】:

    标签: android serialization drawable


    【解决方案1】:

    如果您的Drawables 都是Bitmaps,您可以使用Bitmap.compress() 存储它们

    【讨论】:

      【解决方案2】:

      您应该只需要缓存您从互联网上获取的位图(drawables)。所有其他可绘制对象最有可能在您的 apk 中。

      如果您想将位图写入文件,您可以使用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();
          }
      }
      

      【讨论】:

      • 这似乎可行,但我将如何将存储的图像读回我的应用程序?
      【解决方案3】:

      请参阅http://code.google.com/p/shelves/Google Shleves 项目,他们实际上正在做你想做的事。请查看他们为图像维护 WeakReference 和 SoftReference 的代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 1970-01-01
        • 2014-02-22
        相关资源
        最近更新 更多