2012-07-30 73 views
0

我在我的活动中遇到了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; 
} 

虽然这确实在退出主屏幕活性降低我堆的使用情况,那还不够。由于我使用的其他视图不是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"/> 

感谢您的任何帮助。

回答

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的时候。

1

我会建议延迟加载那些对象,例如BitmapDrawable。尽可能晚地按需提供。此外,当您不再需要它们时,请将对那些BitmapDrawable对象的引用设置为空,并确保您没有其他对这些Bitmap s和Drawable s的引用,以使它们符合垃圾回收的条件。请注意,当垃圾收集器启动时,你无法知道,所以你可以做的就是节省内存。希望这会帮助你。

+0

你是什么意思加载懒惰? – user1132897 2012-07-30 15:30:10

+0

看到这个线程:http://stackoverflow.com/questions/36274/what-is-lazy-loading – overbet13 2012-07-30 16:26:00