2012-07-30 32 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