【问题标题】:Android Dialog, keep dialog open when button is pressedAndroid Dialog,按下按钮时保持对话框打开
【发布时间】:2011-09-02 19:02:59
【问题描述】:

我想在按下按钮时保持对话框打开。 目前它正在关闭。

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

builder.setMessage("Are you sure you want to exit?")

   .setCancelable(false)
   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            MyActivity.this.finish();
       }
   })
   .setNegativeButton("No", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
       }
   });
AlertDialog alert = builder.create();

【问题讨论】:

  • 在根据响应发送登录详细信息后的登录屏幕中显示警报,并再次询问用户名以确认和确定并取消对话框界面按钮。如果用户未在对话框中输入任何内容并单击确定警报对话框被解雇,即使我没有写解雇。一旦我需要检查验证是否为空,那么只有在不为空时才被解雇,否则在edittext上显示seterror请帮助我从前一天开始以不同的方式做
  • 最好disable the button until the user is ready to go on而不是阻止对话框在用户已经点击按钮后关闭。

标签: android dialog


【解决方案1】:

是的,你可以。你基本上需要:

  1. 使用 DialogBu​​ilder 创建对话框
  2. show() 对话框
  3. 在显示的对话框中找到按钮并覆盖它们的onClickListener

所以,创建一个监听器类:

class CustomListener implements View.OnClickListener {
  private final Dialog dialog;

  public CustomListener(Dialog dialog) {
    this.dialog = dialog;
  }

  @Override
  public void onClick(View v) {

    // Do whatever you want here

    // If you want to close the dialog, uncomment the line below
    //dialog.dismiss();
  }
}

然后在显示对话框时使用:

AlertDialog dialog = dialogBuilder.create();
dialog.show();
Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));

请记住,您需要显示对话框,否则将无法找到该按钮。此外,请务必将 DialogInterface.BUTTON_POSITIVE 更改为您用于添加按钮的任何值。另请注意,在 DialogBu​​ilder 中添加按钮时,您需要提供onClickListeners - 但是,您不能在其中添加自定义侦听器 - 如果您不覆盖侦听器,对话框仍将关闭在调用show() 之后。

【讨论】:

  • 如果它已经存在,他为什么要创建一个自定义侦听器?他只需要在“dialog.cancel();”的地方做任何他想做的事。是。
  • @DallaRosa 查看 AlertController 实现。 @Sebastian 这与我所做的相同,我可以确认 Kamen 的答案有效。
  • 感谢提供好的示例,但“私有最终对话框对话框”变量类型应该是 AlertDialog 而不是 Dialog,constrictor 方法参数也应该是 AlertDialog。
  • 我非常讨厌这种方法。在创建按钮时提供侦听器将导致对话框关闭,无论侦听器中有什么。如果您等到它被创建(使用“null”作为侦听器),然后检索按钮并添加侦听器,它会完美运行。感谢您的帮助。
【解决方案2】:

感谢 Sogger 的回答,但我们必须在此处进行一项更改,即在创建对话框之前,我们应该按照传统方式将正按钮(如果需要,还设置负按钮)设置为 AlertDialog,就是这样。

由 Sogger 引用。

这里是示例...

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Test for preventing dialog close");
        builder.setTitle("Test");

        builder.setPositiveButton("OK", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        });
    builder.setNegativeButton("Cancel", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        });

        final AlertDialog dialog = builder.create();
        dialog.show();
        //Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
              {            
                  @Override
                  public void onClick(View v)
                  {
                      Boolean wantToCloseDialog = false;
                      //Do stuff, possibly set wantToCloseDialog to true then...
                      if(wantToCloseDialog)
                          dialog.dismiss();
                      //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
                  }
              });

        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener()
          {            
              @Override
              public void onClick(View v)
              {
                  Boolean wantToCloseDialog = true;
                  //Do stuff, possibly set wantToCloseDialog to true then...
                  if(wantToCloseDialog)
                      dialog.dismiss();
                  //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
              }
          });

【讨论】:

  • 这作为评论或编辑我的答案会更有用......但我想我的答案与原始@Kamen解决方案做了同样的事情,所以c'est生活。
  • @Sogger 对不起,我不想伤害你,但当时我在 stackoverflow 上比较新。但是,正如我在回答开始时声明的那样,这个答案是献给你的。德索莱。
【解决方案3】:

我相信@Kamen 的回答是正确的,这里是一个使用匿名类的相同方法的示例,所以它都在一个代码流中:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
      {            
          @Override
          public void onClick(View v)
          {
              Boolean wantToCloseDialog = false;
              //Do stuff, possibly set wantToCloseDialog to true then...
              if(wantToCloseDialog)
                  dismiss();
              //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
          }
      });

我在https://stackoverflow.com/a/15619098/579234 写了一篇更详细的文章来回答同样的问题,其中还有其他对话框的示例,例如 DialogFragment 和 DialogPreference。

【讨论】:

    【解决方案4】:

    这就是我在更改密码时设法创建持久弹出窗口的方法。

    // Login Activity
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.SetIcon(Resource.Drawable.padlock);
    alert.SetCancelable(false);
    
    var changepass = LayoutInflater.From(this);
    var changePassLayout = changepass.Inflate(Resource.Layout.ChangePasswordLayout, null);
    
    alert.SetView(changePassLayout);
    
    txtChangePassword = (EditText)changePassLayout.FindViewById(Resource.Id.txtChangePassword);
    txtChangeRetypePassword = (EditText)changePassLayout.FindViewById(Resource.Id.txtChangeRetypePassword);
    
    alert.SetPositiveButton("Change", delegate {
        // You can leave this blank because you override the OnClick event using your custom listener
    });
    
    alert.SetNegativeButton("Cancel", delegate {
        Toast.MakeText(this, "Change password aborted!", ToastLength.Short).Show();
    });
    
    AlertDialog changePassDialog = alert.Create();
    changePassDialog.Show();
    
    // Override OnClick of Positive Button
    Button btnPositive = changePassDialog.GetButton((int)Android.Content.DialogButtonType.Positive);
    btnPositive.SetOnClickListener(new CustomListener(changePassDialog, empDetailsToValidate.EmployeeID));
    

    // My Custom Class
    class CustomListener : Java.Lang.Object, View.IOnClickListener, IDialogInterfaceOnDismissListener
    {
        AlertDialog _dialog;
        EditText txtChangePassword;
        EditText txtChangeRetypePassword;
    
        EmployeeDetails _empDetails;
        string _workingEmployeeID;
    
        public CustomListener(AlertDialog dialog, string employeeID)
        {
            this._dialog = dialog;
            this._workingEmployeeID = employeeID;
        }
        public void OnClick (View v)
        {
            _empDetails = new EmployeeDetails(v.Context);
    
            txtChangePassword = (EditText)_dialog.FindViewById (Resource.Id.txtChangePassword);
            txtChangeRetypePassword = (EditText)_dialog.FindViewById (Resource.Id.txtChangeRetypePassword);
    
            if (!(txtChangePassword.Text.Equals(txtChangeRetypePassword.Text))) {
                Show ();
                Toast.MakeText(v.Context, "Password not match.", ToastLength.Short).Show();
            } else if (txtChangePassword.Text.Trim().Length < 6) {
                Show ();
                Toast.MakeText(v.Context, "Minimum password length is 6 characters.", ToastLength.Short).Show();
            } else if ((txtChangePassword.Text.Equals(LoginActivity.defaultPassword)) || (txtChangePassword.Text == "" || txtChangeRetypePassword.Text == "")) {
                Show ();
                Toast.MakeText(v.Context, "Invalid password. Please use other password.", ToastLength.Short).Show();
            } else {
                int rowAffected = _empDetails.UpdatePassword(_workingEmployeeID, SensoryDB.PassCrypto(txtChangePassword.Text, true));
                if (rowAffected > 0) {
                    Toast.MakeText(v.Context, "Password successfully changed!", ToastLength.Short).Show();
                    _dialog.Dismiss();
                } else {
                    Toast.MakeText(v.Context, "Cant update password!", ToastLength.Short).Show();
                    Show();
                }
            }
        }
        public void OnDismiss (IDialogInterface dialog)
        {
            if (!(txtChangePassword.Text.Equals (txtChangePassword.Text))) {
                Show ();
            } else {
                _dialog.Dismiss();
            }
        }
        public void Show ()
        {
            _dialog.Show ();
        }
    }
    

    顺便说一句,我在 Android 上使用 Mono 而不是 Eclipse。

    【讨论】:

      【解决方案5】:

      您不需要创建自定义类。您可以为 AlertDialog 注册一个 View.OnClickListener。此侦听器不会关闭 AlertDialog。这里的技巧是您需要在显示对话框后注册侦听器,但可以在 OnShowListener 中巧妙地完成。您可以使用辅助布尔变量来检查这是否已经完成,以便只执行一次:

      /*
       * Prepare the alert with a Builder.
       */
      AlertDialog.Builder b = new AlertDialog.Builder(this);
      
      b.setNegativeButton("Button", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {}
      });
      this.alert = b.create();
      
      /*
       * Add an OnShowListener to change the OnClickListener on the
       * first time the alert is shown. Calling getButton() before
       * the alert is shown will return null. Then use a regular
       * View.OnClickListener for the button, which will not 
       * dismiss the AlertDialog after it has been called.
       */
      
      this.alertReady = false;
      alert.setOnShowListener(new DialogInterface.OnShowListener() {
          @Override
          public void onShow(DialogInterface dialog) {
              if (alertReady == false) {
                  Button button = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
                  button.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          //do something
                      }
                  });
                  alertReady = true;
              }
          }
      });
      

      【讨论】:

        【解决方案6】:

        您可能需要定义自己的布局,而不是使用“官方”按钮;您要求的行为不是典型的对话。

        【讨论】:

          【解决方案7】:

          你可以得到方法“show()”alertBuidler返回的Dialog。

          AlertDialog.Builder adb = new AlertDialog.Builder(YourActivity.this);
          //...code to add methods setPositive an setNegative buttons
          

          调用“adb”的“show()”方法,得到Dialog

          final AlertDialog dialog = adb.show();
          

          因此,您可以在活动中的任何代码点调用对话框的任何按钮:

          dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();//or
          dialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();//or
          dialog.getButton(DialogInterface.BUTTON_NEUTRAL).performClick();
          

          【讨论】:

            猜你喜欢
            • 2023-04-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-03-08
            • 1970-01-01
            • 2020-09-10
            • 1970-01-01
            • 2021-04-20
            相关资源
            最近更新 更多