单击按钮后关闭AlertDialog框

时间:2013-01-30 16:51:49

标签: java android android-alertdialog layout-inflater

如果没有检测到网络连接,我有以下代码向用户显示一个对话框。

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

}

此对话框中有两个按钮,其中包含为onClick操作定义的方法。我想在按下这些按钮之后关闭对话框弹出窗口。任何想法??

2 个答案:

答案 0 :(得分:1)

是的,自dismiss()引用传递Listener之后,onClickDialogInterface,这可以解雇。

例如

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

或者如果您的按钮位于布局内,请显示对话框并保留对它的引用(final AlertDialog dialog = builder.show())。然后使用dialog.findViewById()查找相应的按钮。分配正常View.OnClickListener并使用您持有的对话框参考调用dismiss()

答案 1 :(得分:0)

试试这个,我使用自定义布局为我工作。感谢Button custon_dialog.findViewById(),然后写OncliclListner()。它会起作用

    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();
        }
相关问题