Devrath
Devrath

Reputation: 42824

Closing alert dialog in android on press of button for first time

What i am doing:

What is happening;

What i want to do:


   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();

}

Upvotes: 4

Views: 1277

Answers (3)

RockStar
RockStar

Reputation: 409

Simple solution is.

You have to move your code for open pop up to some where because whenever you enter in that your activity your onResume() will be call and every time dialog pop up will be open which is wrong. So just move that code somewhere where it execute properly.

NOTE: Call dialog.dismiss() instead of dialog.cancel();

Upvotes: 2

jbiral
jbiral

Reputation: 1459

You don't need to make the dialog pops up in onResume(). onResume() is called everytime the window is focused again. When a dialog pops up, the window loses its focus. When you cancel the dialog, the activity is focused again and onResume() is executed and shows the dialog again.

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

Upvotes: 4

Kostas Drak
Kostas Drak

Reputation: 3260

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 the dialog and i cannot see where you create it

Upvotes: 0

Related Questions