我的活动的onCreate()中有一个alertDialog,它设置了活动的某些属性。
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("My Dialog");
alertDialogBuilder
.setCancelable(false)
...
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
当我启动活动时,会启动对话框,并在提交对话框后设置属性并关闭对话框。到目前为止一切都很好。
但是,如果此时(在提交/取消对话框之后),我旋转设备/屏幕,再次调用onCreate()并再次打开对话框(我不想要)。
如何阻止在屏幕旋转时打开对话框?或者我应该在其他地方创建对话框(而不是在活动的onCreate()中)?
答案 0 :(得分:2)
每次旋转屏幕时都会调用onCreateMethod
问题,您可以覆盖onSaveInstanceState
方法以保存当前版面的实例
boolean isSubmited=false;
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putBoolean(isSubmited, true);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
现在,当您提交对话框时,请将isSubmited
更改为true,然后键入
if(isSubmited)
alertDialog.show();
参考http://developer.android.com/training/basics/activity-lifecycle/recreating.html
答案 1 :(得分:0)
根据Basil Battikhi的解决方案,我最终做了以下事情:
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
// save whether dialog has been submitted
savedInstanceState.putBoolean("isSubmitted", isSubmitted);
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onPause() {
super.onPause();
if ( alertDialog != null ) {
alertDialog.dismiss(); // prevent window leak when screen is rotated while dialog shown
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// check whether activity is recreated or created for the first time
if( savedInstanceState != null ) {
// recover information on whether dialog was submitted
isSubmitted = savedInstanceState.getBoolean("isSubmitted");
}
alertDialogBuilder.setPositiveButton("Start", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
...
isSubmitted=true;
})}
if ( !isSubmitted ) {
alertDialog.show();
}