2016-03-02 65 views
2

如何在appcompact7 alertdialog中進行自定義驗證? 我在alertdialog中有一些輸入,所以當我點擊肯定按鈕時,我想驗證條件是否爲真,萬一條件返回false,我只是想顯示錯誤消息,對話框不應該被解僱。如何防止在Android的正面按鈕點擊時自動解除Appcompact AlertDialog?

試圖this,沒有幫助

alertDialogBuilder 
       .setCancelable(false) 
       .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           if (true) { 
            // Do this and dissmiss 
           } else { 
            // Do not dismiss the dialog 
            errormsg.setVisibility(View.VISIBLE); 
            errormsg.setText("Error"); 
           } 

          } 
         }) 
       .setNegativeButton("Cancel", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           dialog.cancel(); 
          } 
         }); 

     AlertDialog alertDialog = alertDialogBuilder.create(); 
     alertDialog.show(); 

回答

5

你需要重寫肯定按鈕

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

不要在構建器中添加點擊偵聽器。在對話框的onShow()或onStart()中添加偵聽器。

builder.setPositiveButton("Proceed", null); 

@Override 
    public void onStart() { 
     super.onStart(); 
     final AlertDialog dialog = (AlertDialog) getDialog(); 

     if (dialog != null) { 
      Button positiveButton = dialog.getButton(Dialog.BUTTON_POSITIVE); 
      positiveButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
       } 
      }); 
     } 
    } 
+0

不能在此改變在onStart,這上面的解決方案使用android.app.dialog我想使用appcompact – Veer3383

相關問題