如何从视图中释放背景

时间:2012-07-30 14:59:26

标签: android android-layout

我的活动中出现OOM错误问题。我有一个使用两个图像视图和一个约5或6个按钮的布局。目前,我收到了OOM错误,但注意到这些方法的改进。我使用这种方法在主屏幕中设置我的布局:

private void createButtons() 
{
    bitmaps = new ArrayList<Bitmap>();

    ImageView img = (ImageView)findViewById(R.id.homescreen_logo);
    Bitmap bmp = (Bitmap)BitmapFactory.decodeResource(getResources(), R.drawable.homescreen_logo);
    img.setImageBitmap(bmp);
    bitmaps.add(bmp);

    ImageView imge = (ImageView)findViewById(R.id.countdown_labels);
    Bitmap bitmp = (Bitmap)BitmapFactory.decodeResource(getResources(), R.drawable.homescreen_countdown_text);
    imge.setImageBitmap(bitmp);
    bitmaps.add(bitmp);
}

然后,在onPause方法中我调用这个方法:

private void recycleHomescreenImages() {
    for (Bitmap bmap : bitmaps) {
        bmap.recycle();
    }
    bitmaps = null;
}

虽然这会在退出主屏幕活动时降低我的堆使用率,但这还不够。由于我使用的其他视图不是ImageViews,我不能采用仅使用setImageBitmap()方法的相同策略。关于我如何强制收集按钮背景的任何建议?这是我的一个按钮在xml中的样子。

<Button
  android:id="@+id/1_button"
  android:layout_width="294dp"
  android:layout_height="60dp"
  android:layout_alignParentTop="true"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="33dp"
  android:background="@drawable/homescreen_button_1"
  android:onClick="onClick1"/>

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我建议延迟加载BitmapDrawable个对象,例如尽可能晚,按需提供。此外,当您不再需要它们时,将对BitmapDrawable个对象的引用设置为null,并确保没有其他对Bitmap和{{{{ 1}},使它们有资格进行垃圾收集。请注意,您无法知道,当垃圾收集器启动时,所以您可以做的就是节省内存。希望这对你有帮助。

答案 1 :(得分:0)

我实际上只是通过将here的答案修改为以下内容来使其正常工作:

private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
    view.getBackground().setCallback(null);
    view.setBackgroundDrawable(null);
    }
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
        unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
    ((ViewGroup) view).removeAllViews();
    }
}

编辑:谎言,我有时会得到OOM。