節省記憶體的方式就是使用
object = null;
但是,這麼做不一定就能釋放掉記憶體,
因為可能object被其它的元件reference(參照)了。
如果是View上面的ImageView想要完整的被GC掉,
可以試看看View.removeAllView()。
假設今天我有一堆圖片,
想要使用動態的方式增加在LinearLayout上,
而且這個LinearLayout是Vertical排列方式。
  
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //在畫面上放30張圖
        for(int i =0;i<30;i++){
         Bitmap bmp = null;
         bmp = BitmapFactory.decodeResource(getResources(), R.drawable.a55807);
         
         img = new ImageView(this);
         img.setImageBitmap(bmp);
         ll = (LinearLayout) findViewById(R.id.linearLayout1);
         ll.addView(img);
        }
        
    }
 
當使用者按下返回鈕關閉程式時,
覆寫onBackPressed()來清除記憶體,
寫法如下︰
  
   @Override
 public void onBackPressed() {
     //移除畫面上的所有圖 
     ll.removeAllViews();
    super.onBackPressed();
 }
 
經實測,
removeAllView()能最直接的將記憶體清除。
每當再次重開軟體時,
並不會造成記憶體累積。

No comments:
Post a Comment