2014-12-07 124 views
1

我使用AlertDialog.Builder構建我的對話框,它具有需要填充的EditText,並且我想阻止關閉對話框。在正按鈕的onClickListener我可以檢查EDITTEXT填充或沒有,但我不知道如何預防收盤...如何防止AlertDialog關閉?

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

的可能的複製[如何防止關閉一個對話框,點擊一個按鈕時(https://stackoverflow.com/questions/2620444/how-to-prevent-a-dialog-from-closing-當一個按鈕被點擊) – 2017-11-28 10:28:41

回答

21

您可以調用該對話框的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. 
      } 
     }); 
+6

無恥複製代碼從http://stackoverflow.com/questions/2620444/how-to-prevent-a-dialog-from-closing-when-a-button-is-clicked – Antrromet 2014-12-07 17:40:38

+12

無恥地問,沒有研究@ Antrromet – Killer 2015-09-22 11:25:38