在屏幕旋转期间,我正在尝试恢复活动中的错误对话框(从纵向到横向或从横向到横向),这比其他任何事情都要小得多。出现错误时对话框不会正确呈现,但屏幕旋转时对话框不会正确还原。相反,整个屏幕变暗,但什么也看不见。相关代码如下:
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();
}
}
}
我在堆栈溢出上看到的大多数问题/答案都是通过建议使用
DialogFragment
. 当我愿意朝这个方向发展时,我想知道是否没有什么方法可以弥补我当前的代码。