在處理Android視圖時,哪種方式更適合內存管理?我相信第二種方法更好,因爲只有在需要時才能訪問TextView,然後希望收集垃圾。很想聽聽你的意見!Android - 視圖中的類變量vs方法變量
public class MainActivity extends Activity {
TextView tvHelp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvHelp = (TextView) layout.findViewById(R.id.ivHelp);
tvHelp.setText("Started");
}
@Override
public void onResume() {
super.onResume();
tvHelp.setText("Resumed");
}
}
或者這
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvHelp = (TextView) findViewById(R.id.ivHelp);
tvHelp.setText("Started");
}
@Override
public void onResume() {
super.onResume();
TextView tvHelp = (TextView) findViewById(R.id.ivHelp);
tvHelp.setText("Resumed");
}
}
的問題是,我有一個相當大的應用程序,我是這樣做的第一種方式,這成爲堆上非常昂貴,因爲有很多的意見。該應用程序運行緩慢,因爲它使用大量內存來保存這些視圖。我在想第二種方法更好,因爲至少內存使用會更加動態化,並且對象不會停留在周圍,如果它們不被使用 – Nickmccomb
通過使用第二種解決方案確實會獲得一些內存,但我懷疑它是什麼減慢你的應用程序。你在整個應用程序中只使用了1項活動嗎?從一個活動切換到另一個活動時,您持有的視圖/資源將爲GC。你也可以[在IDE的幫助下轉換你的實例變量](http://www.myandroidsolutions.com/2015/01/30/android-studio-tip-2-extract-instance-variable/),看看是否它有什麼區別。 –