屏幕旋转后恢复对话

时间:2018-05-29 11:11:56

标签: android dialog screen-rotation

我遇到的问题不仅仅是在屏幕旋转期间尝试恢复活动中的错误对话框的任何其他问题(纵向到横向,反之亦然)。发生错误时,对话框会正确呈现,但在屏幕旋转时,对话框无法正确恢复。相反,整个屏幕变暗,但没有任何东西可见。以下是相关代码:

private void showErrorDialog() {
    // assume hasErrorDialog is true at this point
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(SomeActivity.this);
    LayoutInflater inflater = SomeActivity.this.getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.dialog_alert, null);
    dialogBuilder.setView(dialogView);
    TextView msgText = (TextView) dialogView.findViewById(R.id.alertMessageText);
    msgText.setText("something went wrong");
    Button okButton = (Button) dialogView.findViewById(R.id.alertOkButton);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            alertDialog.dismiss();
            hasErrorDialog = false;
        }
    });

    alertDialog = dialogBuilder.create();
    alertDialog.show();
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.someActivity);
    int width = rl.getWidth();
    alertDialog.getWindow().setLayout((int) (0.9 * width), ViewGroup.LayoutParams.WRAP_CONTENT);
}

如果在 之后调用上面的方法加载了活动,并且发生了错误,则对话框会加载并完全按照应有的方式运行。因此,在通常条件下调用时,上述代码完全正常工作。

但是,我添加了逻辑,它使用保存的实例状态来试图“记住”实际上应该有一个错误对话框。轮换后,我尝试在检查此实例状态后再次调用上述方法:

protected void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);

    bundle.putBoolean("HASERRORDIALOG", hasErrorDialog);
}

然后在onCreate()我尝试检查此状态,如果存在,请再次致电showErrorDialog()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_activity);

    if (savedInstanceState != null) {
        hasErrorDialog = savedInstanceState.getBoolean("HASERRORDIALOG");

        if (hasErrorDialog) {
            // this does not load the dialog correctly
            showErrorDialog();
        }
    }
}

我在Stack Overflow上阅读的大多数问题/答案都建议使用DialogFragment来解决这个问题。虽然我愿意朝着这个方向前进,但我想知道我目前的代码是否有一些补救办法。

1 个答案:

答案 0 :(得分:0)

运行@MikeM的优秀评论,我意识到问题是我的RelativeLayout活动尚未在onCreate()方法中完全创建,因此它的宽度不是我的期待(可能是零)。

作为一种解决方法,我使用getDisplayMetrics()来访问实际的设备宽度,这在调用onCreate的生命周期中仍然存在:

alertDialog = dialogBuilder.create();
alertDialog.show();
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.90);
alertDialog.getWindow().setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

这里要学到的教训是,在布局中基于某个对话框时,有一个潜在的警告。在这种情况下,在设备轮换失败后尝试在onCreate中恢复该对话框时,这是一种可能的解决方法。

相关问题