0

I have the following code which displays a dialog box to the user if no network connection is detected.

private void createNoNetworkDialog() {

    LayoutInflater inflater = LayoutInflater.from(this);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    View view = inflater.inflate(R.layout.offline_mode_dialog,null);
    builder.setView(view);
    builder.show();

}

There are two buttons in this dialog which have methods defined for their onClick actions. I would like to close the dialog pop-up after either of these button is pressed. Any ideas??

TomSelleck
  • 6,706
  • 22
  • 82
  • 151

2 Answers2

1

Yes,call dismiss() from the Listener's onClick since the DialogInterface reference is passed, which allows for dismissal.

Eg

builder.setPositiveButton ("Yes", new DialogInterface.OnClickListener()
                             {
  public void onClick (DialogInterface dialog, int which)
  {
    //do stuff beforehand
    dialog.dismiss();
  }
});

Or if your buttons are inside the layout, show the dialog and keep a reference to it (final AlertDialog dialog = builder.show()). Then use dialog.findViewById() to find the respective buttons. Assign a normal View.OnClickListener and in it call dismiss() using the dialog reference you're holding.

A--C
  • 36,351
  • 10
  • 106
  • 92
0

Try this, Am using custom layout its working for me. inilitized Button custon_dialog.findViewById() and then write OncliclListner(). It will work

    final Dialog custon_dialog = new Dialog(Login.this);
            custon_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            custon_dialog.setContentView(R.layout.forget_custom_dialog);
            custon_dialog.setCancelable(true);
         Button submit_Btn = (Button) custon_dialog
                    .findViewById(R.id.submit);
        Button cancel_Btn = (Button) custon_dialog
                    .findViewById(R.id.cancel);
       submit_Btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
      //do your stuf
                        }

            });
        cancel_Btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                 custon_dialog.dismiss();
                        }

            });
        custon_dialog.show();
        }
MuraliGanesan
  • 3,233
  • 2
  • 16
  • 22