OnCreate 对话框和屏幕旋转

OnCreate dialog and screen rotation

我的 activity 的 onCreate() 中有一个 alertDialog,它设置 activity 的某些属性。

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();
    }
}

当我启动 activity 时,对话框启动,提交对话框后设置属性并关闭对话框。到目前为止一切顺利。

但是,如果此时(在 submitting/dismissing 对话框之后),我旋转 device/screen,再次调用 onCreate() 并再次打开对话框(我不希望这样).

如何防止在屏幕旋转时打开对话框?或者我应该在其他地方创建对话框(不在 activity 的 onCreate() 中)?

你的问题是每次旋转屏幕时都会调用 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

根据 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();
    }