在alertDialog中对EditText进行验证

时间:2016-10-26 11:35:11

标签: android validation android-edittext alertdialog

我正在EditText上的AlertDialog上添加空字段验证。但即使字段为空,也不会显示错误消息,而是AlertDialog正在关闭。但是如果条件运行良好,因为如果任何一个字段为空,我就无法进行后期操作。

这是我的Java示例代码:

public class TourActivity extends AppCompatActivity {

private LayoutInflater inflater;
private FloatingActionButton fab;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tour);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            inflater = TourActivity.this.getLayoutInflater();
            View content = inflater.inflate(R.layout.activity_add_new_trip, null);
            final EditText editEvent = (EditText) content.findViewById(R.id.edTxt_EventName);
            final EditText editStartDate = (EditText) content.findViewById(R.id.edTxt_EventSDate);


            AlertDialog.Builder builder = new AlertDialog.Builder(TourActivity.this);
            builder.setView(content)
                    .setTitle("Add Event")
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    editEvent.setError(null);
                                    editStartDate.setError(null);

                                    boolean cancel = false;
                                    View focusView = null;

                                    if (TextUtils.isEmpty(editEvent.getText().toString()))) {
                                        editEvent.setError("Please Enter Event Name.");
                                        return;
                                    }

                                    if (TextUtils.isEmpty(editStartDate.getText().toString())) {
                                        editStartDate.setError("Please Enter Event Start Date.");
                                        focusView = editStartDate;
                                        cancel = true;
                                    }


                                    if (cancel == true) {
                                        Snackbar.make(findViewById(android.R.id.content),
                                                "Event Unsuccessful.", Snackbar.LENGTH_LONG)
                                                .setActionTextColor(Color.RED)
                                                .show();
                                        focusView.requestFocus();
                                    } else {
                                        // Some action here
                                    }
                                }
                            })
                    .setNegativeButton(cancel, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });
}
}

3 个答案:

答案 0 :(得分:4)

此答案来自Android Dialog, keep dialog open when button is pressed

正如Dismissing Dialog API Guide所述,

  

当用户触摸使用创建的任何操作按钮时   AlertDialog.Builder,系统为你解开对话框。

因此,您需要创建一个自定义单击侦听器,以防止对话框被关闭。

<强> First Way
您可以阻止正面按钮关闭对话框。你基本上需要:

  1. 使用DialogBu​​ilder创建对话框
  2. show()对话框
  3. 找到显示的对话框中的按钮并覆盖其onClickListener
  4. 所以,创建一个监听器类:

    class CustomListener implements View.OnClickListener {
      private final Dialog dialog;
    
      public CustomListener(Dialog dialog) {
        this.dialog = dialog;
      }
    
      @Override
      public void onClick(View v) {
        // Do whatever you want here
    
        // If you want to close the dialog, uncomment the line below
        //dialog.dismiss();
      }
    }
    

    然后在显示对话框时使用:

    AlertDialog dialog = dialogBuilder.create();
    dialog.show();
    Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    theButton.setOnClickListener(new CustomListener(dialog));
    

    请记住,您需要显示对话框,否则将无法找到该按钮。此外,请务必将 DialogInterface.BUTTON_POSITIVE 更改为用于添加按钮的任何值。另请注意,在DialogBuilder中添加按钮时,您需要提供onClickListeners - 您无法在其中添加自定义侦听器 - 如果您在之后未覆盖侦听器,则对话框仍会被忽略show()被称为。{/ p>

    <强> Second Way

    以下是使用匿名类的相同方法的示例,因此它只在一个代码流中:

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Test for preventing dialog close");
    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)
              dismiss();
           //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
           }
        });
    

答案 1 :(得分:0)

这是在AlertDialog中验证输入密码的方法。

请确保您为密码创建了一个单独的xml布局文件,该文件只有一个组件/视图为EditText,可以从用户那里获取密码。

为输入密码创建布局后,我们将使用Dialog扩展该布局,以将自定义视图设置为AlertDialog。

Inflater inflater = new Inflater(this);
View myPasswordView = inflater.inflate(R.xml.my_custom_password_layout);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Password");
//alertDialogBuilder.setMessage("Enter password to open Application.");
alertDialogBuilder.setView(myPasswordView);

alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                // Do not use this place as we are overriding this button later in the cade.
            }
        }); alertDialogBuilder.setPositiveButton("Cancel", 
        new DialogInterface.OnClickListener({
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                // Dismiss dialog and close activity if appropriated, do not use this (cancel) button at all. 
                dialog.dismiss();
            }
        });

final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
// Overriding the that button here immediatly handle the user's activity.
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
      {            
          @Override
          public void onClick(View v)
          {
              Boolean isError = false;
              //Do your job here. For example we are checking the input password.
              final EditText txtPassword = myPasswordView.findViewById(R.id.txtPassword);
              String password = txtPassword.getText().toString().trim();
              Boolean isError = true;

              // Check password if not empty. You can add another IF statement to do your logic for password validation.
              if(password.isEmpty()) {
                  isError = true;
                  txtPassword.setError("Password cannot be empty");
              }
              if(password.equals("1234") {
                  // You password is correct. 
                  isError = false;
                  txtPassword.setError(null);
              }
              if(!isError)
                  dialog.dismiss();
              // Otherwise the dialog will stay open.
          }
      });

答案 2 :(得分:-1)

试试这样:

if (TextUtils.isEmpty(edEvent)) {
    editEvent.setError("Please Enter Event Name.");
    editEvent.requestFocus();
    return;
}