简体   繁体   中英

How Do I keep an AlertDialog box open if a user types invalid data in Edittext?

I have an alertDialog box that asks the user to enter their full name and email. I am trying to validate the data and if the data is invalid, I would like to display the dialog box again with the error messages (like you do with Edittext fields in android). How would I do that inside the OK button? Here is my code:

final AlertDialog.Builder zoomDialog = new AlertDialog.Builder(new ContextThemeWrapper(activity, android.R.style.Theme_DeviceDefault_Light_Dialog));
                LayoutInflater factory = LayoutInflater.from(activity);
                final View f = factory.inflate(R.layout.name_and_email, null);

                zoomDialog.setTitle("Please enter your name and email");
                zoomDialog.setView(f);
                zoomDialog.setPositiveButton("SUBMIT", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int which) {
                        ((onFollowedListener) activity).onFollowed();


                        EditText full_name = (EditText)f.findViewById(R.id.follower_name);
                        EditText email_address = (EditText)f.findViewById(R.id.follower_email);

                        String follower_name = full_name.getText().toString();
                        String follower_email = email_address.getText().toString();
                        Validator validator = new Validator();
                        if(validator.validateFullName(follower_name) && validator.validateEmail(follower_email)){
                            Toast.makeText(activity, follower_name + " " + follower_email,
                                    Toast.LENGTH_LONG).show();
                        }else {
                            full_name.setError("** Required: Please enter your name and email");
                            full_name.requestFocus();
                            Toast.makeText(activity,  " Please enter your name and email! " ,
                                    Toast.LENGTH_LONG).show();
                            return;
                        }



                        Intent intent = new Intent(activity, RewardActivity.class);
                        intent.putExtra("type", "followers");
                        startActivity(intent);

                    }
                });

                zoomDialog.show();

Every time I click SUBMIT (POSITIVE) button, the dialog box is dismissed. I would like to keep it open so the user can reenter the information required instead of returning to where they began.

If I could call the show() method inside the else clause, it would be easier but it does not work!

Any help will be highly appreciated. Thanks in advance.

我建议使用editText和button建立一个自定义对话框,您可以注册onClick并在关闭它之前执行所需操作, 请在此处查看更多详细信息

You might also try using a textchangelistener. You can set up an EditText to provide errors on a field, complete with a popup on the EditText object. When an error occurs, EditText manages the popup. As long as the user keep putting in wrong data, the popup stays.

For example, here's one that listens to a username field:

    // setup text watcher to prevent unwanted chars from username
    userNameET.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO - nothing
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO - nothing
        }

        public void afterTextChanged(Editable s) {

            // only check for non-null or max length
            if (userNameET.getText().toString().isEmpty()) {
                userNameET.setError("User name\n"+getString(R.string.required));
            }
            else if (userNameET.getText().toString().length() > MAX_NAME) {
                userNameET.setMaxLengthError(String.format("User name\n"+getString(R.string.too_long), MAX_NAME));
            }
            else {
                userNameET.setError(null);
            }


            // Allow alphanumerics, "@" "." "-" "_" all others will be discarded
            String input = s.toString();
            String inputAfter = input.replaceAll("[^-A-Za-z0-9@_.]", "");

            if (!inputAfter.equals(input)) {
                // we changed something
                Log.d("REGEX", "not valid " + input);
                userNameET.setText(inputAfter);
            }
        }
    });

I use the afterTextChanged method to change any unwanted characters. You'll notice also that when I encounter an error, I setError(error) with the string to tell the user what's wrong or null to clear the error.

First of all, thank you guys for the help here. I was able to fix this issue! Here is what I ended up with:

//some AlertDialog.Builder code here

Button submit = (Button)f.findViewById(R.id.follower_submit);

                submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Validator validator = new Validator();

                        EditText full_name = (EditText)f.findViewById(R.id.follower_name);
                        EditText email_address = (EditText)f.findViewById(R.id.follower_email);

                        String follower_name = full_name.getText().toString();
                        String follower_email = email_address.getText().toString();

                        boolean validName = validator.validateFullName(follower_name);
                        boolean validEmail = validator.validateEmail(follower_email);

                        if(!validName || !validEmail){
                            if(!validName){
                                full_name.setError("** Please enter a valid name");
                            }

                            if(!validEmail){
                                email_address.setError("** Please enter a valid email address");
                            }
                        } else {
                            if(activity instanceof FollowersActivity){
                                ((FollowersActivity) activity).clearIcons();
                            }

                            Intent intent = new Intent(activity, RewardActivity.class);
                            intent.putExtra("type", "followers");
                            startActivity(intent);
                        }

                    }
                });

dialog.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM