2016-03-02 71 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

相关问题