【问题标题】:Recycle drawable of Imagebutton回收Imagebutton的drawable
【发布时间】:2013-09-11 19:48:00
【问题描述】:

在我的“主屏幕”片段中,我有几个图像按钮。 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

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

有人知道解决办法吗?

【问题讨论】:

  • 在清单文件的应用标签中添加 android:largeHeap = "true" 然后运行你的项目。
  • 您的图片有多大?您可能已经在窥探您的内存使用情况。
  • 我会在别处寻找内存泄漏
  • @gunar 一个 PNG 大约 4kb,所以它们非常小。
  • @FunkTheMonk 我不太明白你的意思,LogCat 很清楚这与位图有关,对吧?

标签: android


【解决方案1】:

在清单文件的应用程序标签中添加 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.
}

【讨论】:

  • 我认为这不是一个合适的解决方案。我的应用程序是一个轻量级应用程序,不需要大堆。此外,这在 API lvl 11 中可用,我的最低 lvl 为 8。
  • 然后在 onDestroy 方法中回收位图,无论您在哪里设置 imagebutton 图像,请在我的答案中检查此条件。
  • 至于您的编辑:您将 ImageButton 投射到 BitmapDrawable 那里,这是行不通的。你确定这对你有用吗?
  • ((BitmapDrawable)imagebutton.getDrawable()).getBitmap().recycle();使用这条线获得可回收利用
猜你喜欢
  • 2017-05-29
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多