Shobhit
Shobhit

Reputation: 417

Android: Is it possible not to close the AlertDialog.Builder automatically?

I have an alertDialogBuilder of type AlertDialog.Builder. This has two buttons, one positive and another one negative. When the positive button is clicked, I have a condition check and if it is successful, only then the alertDialogBuilder should be closed else the android app should keep displaying it. Is this possible?

Current code

EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setTitle("test");
    alertDialogBuilder.setMessage("testMessage");
    alertDialogBuilder.setCancelable(false);                        
    editText = new EditText(this);
    editText.setText("hi");
    alertDialogBuilder.setView(editText);
    editText.requestFocus();

    alertDialogBuilder.setNegativeButton("Cancel", dialogLinstener);
    alertDialogBuilder.setPositiveButton("Save", dialogLinstener);

    alertDialogBuilder.show();
}

private DialogInterface.OnClickListener dialogLinstener = new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {            
        if(which == DialogInterface.BUTTON_POSITIVE) {

            String str = editText.getText().toString();
            if(!str.equals("hi")) {

                               // do something..

            } else {

                               // do something else..

            }
        } else if (which == DialogInterface.BUTTON_NEGATIVE) {
            //do nothing.
        }

        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null)
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

        return;
    }
};

Upvotes: 0

Views: 963

Answers (2)

Rohan Kandwal
Rohan Kandwal

Reputation: 9336

If you mean by not to close the AlertDialog.Builder automatically that is should not close when clicked outside then you can do the following :-

dialog.setCanceledOnTouchOutside(false);

If you just want to only close the dialog when a condition is met then keep a reference to AlertDialog that the AlertDialog.Builder creates as @Ascorbin correctly said then in your condition

if(condition == true){
//code
dialog.dismiss();
}

This way dialog will only close if condition is met.

Upvotes: 0

fweigl
fweigl

Reputation: 22038

Keep a reference to the AlertDialog that the AlertDialog.Builder creates. You can then show or dismiss the AlertDialog as you please.

AlertDialog dialog =  alertDialogBuilder.create(); 
dialog.show(); 

and then somewhere else:

dialog.dismiss(); 

Upvotes: 1

Related Questions