AlertDialog 横竖屏切换报WindowLeaked / dialog消失

解决办法:
1、在onDestroy添加如下代码

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (alertDialog1 != null)
            alertDialog1.dismiss();
    }

2、在onSaveInstanceState方法,在activity销毁前,判断dialog是否显示,如果显示设置一个标识,代码

  @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (alertDialog1 != null && alertDialog1.isShowing())
            outState.putBoolean("FLAG", true);
    }

3、在onRestoreInstanceState方法,显示dialog,代码

   @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
            boolean dialog_shown = savedInstanceState.getBoolean("FLAG");
            if (dialog_shown){
                showDialog();}
    }

这样AlertDialog,不会泄露也不会切换屏幕后消失

附:showDialog方法

 private void showDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
                .setTitle("对话框")
                .setMessage("正在加载哟...")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(), "cancle", Toast.LENGTH_SHORT).show();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(), "sure", Toast.LENGTH_SHORT).show();
                    }
                });
        alertDialog1 = alertDialog.create();
        alertDialog1.show();
    }

你可能感兴趣的:(AlertDialog 横竖屏切换报WindowLeaked / dialog消失)