android - 如何防止 AlertDialog 关闭?

标签 android onclicklistener android-alertdialog

我正在使用 AlertDialog.Builder 构建我的对话框,它有一个需要填充的 EditText,我想防止在对话框未关闭时关闭它。在肯定按钮的 onClickListener 中,我可以检查 editText 是否已填充,但我不知道如何防止关闭...

builder.setPositiveButton("title", new DialogInterface.OnClickListener(){
     @Override
     public void onClick(DialogInterface dialog, int which) {
           if(...){
              //can close
           }else{
            //prevent closing
           }
     }
})

最佳答案

您可以在调用对话框的 show() 后立即更改按钮的行为,如下所示。

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test", 
        new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                //Do nothing here because we override this button later to change the close behaviour. 
                //However, we still need this because on older versions of Android unless we 
                //pass a handler the button doesn't get instantiated
            }
        });
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.
          }
      });

关于android - 如何防止 AlertDialog 关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27345584/

相关文章:

android - 屏幕方向更改后继续 Activity - Android

java - 类/监听器之间的通信

javascript - Openlayers 3` 中绘制功能的单击事件处理

android - 在 Activity 中获取 Activity

Android:如何临时呈现以编程方式创建的位图以进行调试?

java - 我想用 Java 为 Android 解析 JSON,但 Gson 和 Jackson 都无法正常工作

java - 如何搜索和过滤 fragment 中的文本

android - 使用处理程序发布到 UI 线程

java - 如何从 BroadcastReceiver 内部打开 Wifi 设置

android - 如何在键盘显示屏上调整 AlertDialog 的大小