如何防止AlertDialog关闭? [英] How to prevent AlertDialog to close?

查看:206
本文介绍了如何防止AlertDialog关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AlertDialog.Builder来构建对话框,它具有一个EditText,必须填充该文本,并且我想防止在没有对话框的情况下关闭该对话框.在肯定按钮的onClickListener中,我可以检查editText是否已填充,但是我不知道如何防止关闭...

I'm using AlertDialog.Builder to build my dialog, it has an EditText which is necessary to be filled and I want to prevent closing the dialog while it is not. In the positive button's onClickListener I can check if the editText is filled or not but I don't know how to prevent closing...

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

推荐答案

您可以在调用对话框的show()之后立即更改按钮的行为.

You can change the behavior of the button immediately after calling show() of the dialog, like this.

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

这篇关于如何防止AlertDialog关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆