1

在我的“主屏幕”片段中,我有几个 Imagebuttons。Imagebutton 的 XML 是:

                <ImageButton
                    android:id="@+id/merkzettel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:background="#00000000"
                    android:scaleType="fitXY"
                    android:src="@drawable/dashboard_merkzettel_icon__selector" />

可绘制的 XML 选择器如下所示:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_startseite_merkzettel_on"
          android:state_pressed="true" />
    <item android:drawable="@drawable/icon_startseite_merkzettel_off" />
</selector>

在较旧的设备(Nexus S)上,当我将设备翻转一段时间(更改屏幕方向)时,出现异常:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
    at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:460)
    at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336)
    at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
    at android.content.res.Resources.loadDrawable(Resources.java:1709)
    at android.content.res.Resources.getDrawable(Resources.java:581)
etcetc

这似乎是一个常见问题,因为每次重新创建 Activity / Fragment 时,Android 都会重新创建可绘制的位图,而对于 Drawables,推荐的解决方案是针对drawable.recycle()它们,onDestroy()但我找不到合适的方法来控制 ImageButton 的可绘制对象.

有谁知道这个的解决方案?

4

1 回答 1

2

在清单文件的应用程序标签中添加 android:largeHeap = "true" 然后运行您的项目。

像下面

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Light.NoTitleBar"
    android:largeHeap="true">
<application/>

在销毁方法中

@Override
protected void onDestroy() {
    super.onDestroy();
    ((BitmapDrawable)imagebutton.getDrawable()).getBitmap.recycle();
}

并在 onCreate 方法中检查这一点。

if (imagebutton.getDrawable() == null){
  // set your image button image here.
} else {
  // nothing to do.
}
于 2013-09-11T10:06:07.917 回答