如何在Android中从内存中释放(强制,如果需要)9-patch(NinePatchDrawable)?

Cor*_*ese 12 android

你如何强制NinePatchDrawable释放它从'res'解析出来的BitMap字节?


作为Android开发人员,我面临着控制游戏内存利用率的压力.

我通过在不再使用资源后尽快释放资源来控制内存利用率.为此,我保留了所有已加载资源的列表,并在完成后立即从内存中清除/释放它们.

我的应用程序使用了许多不同类型的图形资源

  • 的BitMap
  • BitMapDrawable
  • 可绘制
  • NinePatchDrawable

我现在如何发布这些对象?

  • BitMap:我使用"recycle()"方法
  • BitMapDrawable:我使用"getBitMap().recycle()"方法
  • Drawable:我将它们设置为null(不工作)
  • NinePatchDrawable:我将它们设置为null(不工作)

你有什么尝试?

  • 你不能"getBitmap()"一个NinePatchDrawable
  • 你不能将NinePatchDrawable转换为BitMapDrawable(即使它们都是基于Bitmap的Drawables)
  • 似乎有一种方法可以自己解析PNG,自己将字节输入NinePathDrawable - 这可能会让我自己能够"回收()"自己的底层BitMap,但这似乎是我重新发明了轮(http://code.google.com/p/android/issues/detail?id=13542)

我目前的规则:

  • 切勿在XML中使用@ drawable /
  • 从来没有android:XML背景
  • 从来没有android:src在XML中

Ent*_*eco 2

为了能够在 xml 中使用:@drawable/、android:background、android:src,您始终可以使用自定义类。

所以 <ImageView android:src="@drawable/bg" /> 你可以使用: <com.myPackage.CustomImageView android:src="@drawable/bg" />

比在构造函数中的 CustomImageView 中,您可以获得对 xml 属性的引用:

    
private Drawable bg2;
private Drawable bg1;
public void CustomImageView(Context context, Attrs attrs)
{
    super(context, attrs);

    // Use this to get references to your xml attributes
    int resourceId = attrs.getAttributeResourceValue("android", "src", 0);
    bg1 = getResources().getDrawable(resourceId);

    // Or for the 'background' attribute
    resourceid = attrs.getAttributeResourceValue("android", "background", 0);
    bg2 = getResources().getDrawable(resourceId);

    // Now you can recycle() your 'bg' whenever you're done
}
Run Code Online (Sandbox Code Playgroud)

这样,您就可以从 xml 中提取引用。当你认为合适时回收()它们