为什么一些AlertDialogs会在设备轮换时消失?

Vio*_*ffe 1 user-interface android

当我更改设备方向时,如果显示AlertDialog,它将消失.对于我的应用程序中除了一个对话框之外的所有对话框都是如此,我无法弄清楚那些不会消失的内容以及如何抵消这种行为.是否有可能在方向改变时保留对话(手动管理除外)?

tod*_*odd 8

您还可以覆盖onSaveInstanceState方法并保存一个标志,指示方向更改时对话框是否显示.然后,您可以从onCreate中的包中取回该标志,并在需要时重新显示对话框.

@Override
protected void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);

    // Save the state so that it can be restored in onCreate or onRestoreInstanceState
    state.putBoolean("dialog_showing", dialog_showing);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    if(savedInstanceState != null && savedInstanceState.getBoolean("dialog_showing", false)) {
        // Show your dialog again
        ...
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

编辑:

onCreate您可以覆盖该onRestoreInstanceState方法,而不是恢复您的状态.它被调用onStart,只有在bundle不为null时才会被调用; 所以你不必像在onCreate方法中那样对bundle进行null检查.

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    if(savedInstanceState.getBoolean("dialog_showing", false)) {
        // Show your dialog again
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*oet 5

正如这里许多人所建议的那样,

android:configChanges="keyboardHidden|orientation"
Run Code Online (Sandbox Code Playgroud)

不是解决方案。这充其量是一个黑客。处理此问题的正确方法是通过您的活动管理对话框。您需要在活动代码中覆盖一些方法,如下所示:

protected Dialog onCreateDialog(int id) {
    // create and return your dialog instance here
    AlertDialog dialog = new AlertDialog.Builder(context)
        .setTitle(title)
        .setIcon(R.drawable.indicator_input_error)
        .setMessage(message)
        .create();
    dialog.setButton(
            DialogInterface.BUTTON_POSITIVE,    
            context.getString(R.string.OK),
            (DialogInterface.OnClickListener) null);
    return dialog;
}

protected void onPrepareDialog(int id, Dialog dialog) {
    // You dialog initialization code here
}
Run Code Online (Sandbox Code Playgroud)

做完这件事后。您使用以下方法显示对话框:

showDialog(yourDialogID);
Run Code Online (Sandbox Code Playgroud)

完成此操作后,您将看到如果发生配置更改,您的对话框也将重新创建。最好的部分是您Activity将为您管理对话。如果可能,它将被重用,如果您执行大量初始化,则减少对话框加载时间。

Android SDK 文档中的注意事项: 应避免使用此属性,并且仅将其用作最后的手段。请阅读处理运行时更改以获取有关如何正确处理由于配置更改而重新启动的更多信息。