且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android对话框,当按下按钮时,保持对话框打开

更新时间:2022-12-19 16:03:52

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

Yes, you can. You basically need to:


  1. 使用 DialogBu​​ilder
  2. 创建对话框
  3. show()对话框

  4. 找到所显示对话框中的按钮,并覆盖他们的 onClickListener

  1. Create the dialog with DialogBuilder
  2. show() the dialog
  3. Find the buttons in the dialog shown and override their onClickListener


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

So, create a listener class:

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

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

Then when showing the dialog use:

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()后,如果不覆盖监听器,对话框仍然会被关闭。

Remember, you need to show the dialog otherwise the button will not be findable. Also, be sure to change DialogInterface.BUTTON_POSITIVE to whatever value you used to add the button. Also note that when adding the buttons in the DialogBuilder you will need to provide onClickListeners - you can not add the custom listener in there, though - the dialog will still dismiss if you do not override the listeners after show() is called.