Skip to content Skip to sidebar Skip to footer

Alert Dialog Was Disappearing When User Clicks Out Side

Hi everyone i have a alert box with two text box's, and here the problem is the alert dialog was disappearing when user clicks outside of that pop up or the Alert dialog is disappe

Solution 1:

because by default it is Cancelable

Add this after builder.setView(linearLayout) -

builder.setCancelable(false);

UPDATE

As per your code snippet below-

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

on positive button ("OK") click, you are setting dialog.cancel() Don't do this, you should set some action as you required on positive button click.

See This :

builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel(); // close the current dialog
        }
    });

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

           //Perform any Intent Action or perform validation as you want

         }
    });

UPDATE 2

Just copy & paste below code - working perfectly

 final EditText input1 = new EditText(MainActivity.this);
        final EditText input2 = new EditText(MainActivity.this);
        input1.setHint("Enter name1");
        input2.setHint("Enter Name2");
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(input1);
        linearLayout.addView(input2);

        final AlertDialog builder = new AlertDialog.Builder(MainActivity.this)
                .setTitle("Sign In Failed")
                .setCancelable(false)
                .setMessage("Invalid username or password").setView(linearLayout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).create();
        builder.show();
        builder.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (input1.length() <= 0) {
                    Toast.makeText(MainActivity.this, "Please Enter Name", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
                    builder.dismiss();
                }
            }
        });

Solution 2:

You need to set outside touch false try this:

setCanceledOnTouchOutside(false);

Solution 3:

Simply set cancelable false:

.setCancelable(false)

Post a Comment for "Alert Dialog Was Disappearing When User Clicks Out Side"