Android 如何从视图中释放背景

Android 如何从视图中释放背景,android,android-layout,Android,Android Layout,我的活动中有OOM错误问题。我有一个布局,它使用两个ImageView和大约5或6个按钮。目前,我得到一个OOM错误,但注意到这些方法的改进。我使用此方法在主屏幕中设置布局: private void createButtons() { bitmaps = new ArrayList<Bitmap>(); ImageView img = (ImageView)findViewById(R.id.homescreen_logo); Bitmap bmp =

我的活动中有OOM错误问题。我有一个布局,它使用两个ImageView和大约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);
}
虽然这确实降低了退出主屏幕活动时的堆使用率,但这还不够。因为我使用的其他视图不是ImageView,所以我不能使用与使用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"/>


感谢您的帮助。

我建议延迟加载那些
位图
可绘制的
对象,例如,根据需要尽可能晚地加载。另外,当您不再需要这些对象时,请将对这些
Bitmap
Drawable
对象的引用设置为null,并确保没有对这些
Bitmap
Drawable
对象的其他引用,以使它们符合垃圾收集的条件。请注意,您无法知道垃圾回收器何时启动,因此这是您为节省内存所能做的一切。希望这会对您有所帮助。

实际上,我只是能够通过将中的答案修改为如下所示来让它工作:

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();
    }
}
private void unbindDrawable(视图){
if(view.getBackground()!=null){
view.getBackground().setCallback(null);
视图.setBackgroundDrawable(空);
}
if(视图组的视图实例){
对于(int i=0;i<((视图组)视图)。getChildCount();i++){
未绑定的Drawables(((视图组)视图).getChildAt(i));
}
((视图组)视图);
}
}

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

你说的懒散加载是什么意思?
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();
    }
}