【发布时间】:2015-09-19 08:17:52
【问题描述】:
在 Activity 中,我以编程方式创建布局(根本没有 layout.xml)并从可绘制对象池中为其分配可绘制对象,然后销毁所述 Activity,除非我这样做,否则内存不会被 GC 处理
layout.getBackground.setCallback(null);
layout.setBackground(null);
我在哪里可以找到关于为什么会发生这种情况以及为什么 layout.xml 和以编程方式创建的布局之间存在差异的解释?在第一种情况下,出于某种原因,我不必调用 setBackground(null)。
更新:以下代码
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
//Setting up UI
layout = new LinearLayout(context);
layout.setBackgroundDrawable(Stuff.getRandomDrawable(ManageCities.this));
cityUpdater = new Button(context);
cityRemover = new Button(context);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setTitle(R.string.pls_wait);
progressDialog.setCancelable(false);
cityUpdater.setText(R.string.update_city_list);
cityRemover.setText(R.string.remove_city);
cityRemover.setOnClickListener(this);
cityUpdater.setOnClickListener(this);
database = WalkerDatabase.getInstance(
getSharedPreferences(FirstActivity.getPrefsName(), 0).
getString("datapath", null));
adapter = database.getItems();
layout.setOrientation(LinearLayout.VERTICAL);
ur = new WifiUpdateReciever(cityUpdater);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(ur, intentFilter);
if (adapter.isEmpty()) {
cityRemover.setEnabled(false);
}
layout.addView(cityUpdater);
layout.addView(cityRemover);
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!Stuff.isRunningOnEmulator()) {
if (!mWifi.isConnected()) {
Toast.makeText(this, getString(R.string.wifi_disabled), Toast.LENGTH_LONG).show();
cityUpdater.setEnabled(false);
cityUpdater.setClickable(false);
}
}
setContentView(layout);
}
【问题讨论】:
-
替换:
Context context = getApplicationContext();为Context context = this; -
pskink,谢谢。阅读上下文。
标签: android android-layout android-memory