Closing alert dialog in android when clicking a button for the first time

What am I doing:

  • I am launching a dialog using below code
  • On click, I want to close the dialog

What's happening,

  • The dialog closes, but I have to click OK twice (it looks like the warning appears twice, but the second time it closes, I click ok)

What I want to do:

  • I want to close the dialog when I click OK for the first time

   public void open(String custMsg){

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setMessage(custMsg);
    alert.setCancelable(false);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {

        dialog.cancel();
      }
    });
    alert.show();

}

      

+3


source to share


3 answers


You don't need dialog to pop up in onResume()

. onResume()

called every time the window is focused again. When the dialog box appears, the window loses focus. When you cancel the dialog, the activity will focus again and onResume()

be executed and display the dialog again.



Call the dialog somewhere else and it will work (for example onStart()

)

+3


source


A simple solution.

You need to move your code for the popup popup somewhere because whenever you enter this activity your call onResume()

will be called and every time the dialog is opened, which is not correct. So just move this code somewhere where it runs correctly.



NOTE: Call dialog.dismiss()

insteaddialog.cancel();

+2


source


Try this better

public AlertDialog open(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this,
                AlertDialog.THEME_DEVICE_DEFAULT_DARK);
        builder.setTitle(R.string.about_title)
                .setMessage(msg)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).show();

        return builder.create();
    }

    }

      

But you also need to create a dialog and I can't see where you are creating it.

0


source







All Articles