如何使用OnDismiss才能使用对话框输入?

时间:2015-02-06 07:58:33

标签: android user-input dialog

我有一个用户对话框提示,用户输入将在代码的下一步中使用。我试图使用OnDismiss使其余的代码接受用户输入。以下是代码段:

AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle("Title");
    alert.setMessage("Message");

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {

        input = 3;
      }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
          input = 1;
      }
    });

    alert.show();

    }

public void OnDismiss(DialogInterface dialogInterface)
{
Toast.makeText(this, "Input: " + input, Toast.LENGTH_LONG)
.show();

}

但是,当我按下对话框按钮时,对话框将被取消,但不显示吐司。请在这里建议我做错了什么。

2 个答案:

答案 0 :(得分:1)

首先将OnDismissListener设置为AlertDialog,然后在按下对话框按钮时调用dismiss(),代码如下:

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle("Title");
    alert.setMessage("Message");

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        input = 3;
        dialog.dismiss();
      }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
          input = 1;
          dialog.dismiss();
      }
    });

   alert.setOnDismissListener(new OnDismissListener(){
       public void OnDismiss(DialogInterface dialogInterface)
         {
          Toast.makeText(this, "Input: " + input, Toast.LENGTH_LONG)
         .show();
          }
   });

    alert.show();

答案 1 :(得分:0)

你必须使用dialog.dismiss();

  alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int whichButton) {

    input = 3;
   dialog.dismiss();
  }
});

  alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int whichButton) {
      input = 1;
  dialog.dismiss();
  }
});