为什么alertdialog无法关闭?

时间:2019-02-16 02:56:19

标签: android android-alertdialog

此代码有什么问题?为什么在按下ok

时不能关闭警报对话框
 protected void loadDialogBox(Context context, String title, String message) {
    try {
        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setTitle(title);
        dialogBuilder.setMessage(message);          
        dialogBuilder.setPositiveButton("OK", (dialogInterface, i) -> {
            Log.i(TAG,"Ok is clicked");
            fragmentManager.popBackStackImmediate();
            dialogInterface.dismiss();

        });
        final AlertDialog dialog = dialogBuilder.create();
        dialog.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:0)

尝试使用此代码,无需调用dismiss设置onclick完成后自动设置正负按钮对话框:

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
                dialogBuilder.setTitle("New Item");
                dialogBuilder.setMessage("Enter Item Details");
                dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                });
                dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //pass
                    }
                });
                AlertDialog b = dialogBuilder.create();
                b.show();

答案 1 :(得分:0)

  

将代码更改为

protected void loadDialogBox(Context context, String title, String message) {
    try {
        final AlertDialog.Builder dialogBuilder = new 
        AlertDialog.Builder(context);
        dialogBuilder.setTitle(title);
        dialogBuilder.setMessage(message);   
       final AlertDialog dialog = dialogBuilder.create();       
        dialogBuilder.setPositiveButton("OK", (dialogInterface, i) -> {
            Log.i(TAG,"Ok is clicked");
            fragmentManager.popBackStackImmediate();
            dialog.dismiss();

        });

        dialog.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}