问题
protected Dialog onCreateDialog(int id) {
...
AlertDialog.Builder adb = new AlertDialog.Builder(this);
...
mydialog = adb.create();
...
}
But onCreateDialog runs after onCreate.
回答1:
If you want to be backwards compatible, you do it as follows.
class MyActivity extends Activity {
protected static final class MyNonConfig {
// fill with public variables keeping references and other state info, set to null
}
private boolean isConfigChange;
private MyNonConfig nonConf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
nonConf = (MyNonConfig)getLastNonConfigurationInstance();
if (nonConf == null) { nonConf = new NonConfig(); }
// handle the information of the nonConf objects/variables
...
}
@Override
protected void onStop() {
super.onStop();
isConfigChange = false;
}
@Override
public Object onRetainNonConfigurationInstance() {
isConfigChange = true;
return nonConf;
}
@Override
protected void onDestroy() {
super.onDestroy();
// handle objects in nonConf, potentially based on isConfigChange flag
...
}
The nonConf objects will survive all configuration changes (but not real stops of your app). Also, the isConfigChange flag tells you reliably if your activity is going to be re-created immediately or not. Thus, you can cancel/detach tasks or handle other resources adequately based on this information.
Edit: Please note that if onDestroy()
is called then you can rely on the isConfigChange
flag. Also, if Android is processing a configuration change then onDestroy()
will be called. However, if Android is about to end your activity then the call to onDestroy() is optional because Android considers your activity to be killable right after it calls onPause()
(pre-Honeycomb) or onStop()
(Honeycomb and beyond). That's not a problem though, because if your activity is going to be killed, the state of your numerous objects isn't interesting to anyone anymore. However, if you want to be friendly, this is one more aspect to consider regarding the decision what to put into onPause()
and onStop()
.
Hope this helps.
来源:https://stackoverflow.com/questions/14374093/how-to-save-restoreupdate-ref-to-the-dialog-during-screen-rotationi-need-ref