TextWatcher中的edittext问题

时间:2014-11-24 08:21:12

标签: java android android-edittext textwatcher

我正在尝试配置一个简单的表单。我有3个editexts,在用户结束输入后,我想显示已检查的图标,如果它有效(并进入下一个字段),如果没有,则显示错误,用户可以更正。

我的主要问题是我只能输入1个字符,然后显示我或错误或选中图标,然后它会转到下一个字段。

我做错了什么?

这是我的代码:

public class ConTct extends Activity implements OnClickListener, OnTouchListener{

    Button mButton;
    EditText mFullName, mEmail, mDialZone, mPhone;
    static WebView mWebView;
    static ProgressBar mProgressBar;
    EditText mBrokerId, mIP, mAreaPhonePrefix, mLastName, mPassWord, mCampaign, mSubCampaign, mCountryID, mCity, mAdress, mIsDemo;

    private String inputText;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.contct);

        registerViews();


    }//oncreate()


        private void registerViews(){
    mFullName = (EditText) findViewById(R.id.firstName);
    mFullName.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                //do nothing
            }else{
                if(!Validation.hasText(mFullName)){
                    mFullName.setError("You have to input at least 3 characters");
                    mFullName.requestFocus();
                }else{
                    mFullName.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
                    mFullName.clearFocus();

                    mEmail.requestFocus();
                }
            }
        }
    });

    mEmail = (EditText) findViewById(R.id.email);

    mEmail.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                //do nothing
            }else{

                if(!Validation.isEmailAddress(mEmail, true)){
                    mEmail.setError("wrong email");
                    mEmail.requestFocus();
                }else{
                    mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
                    mEmail.clearFocus();

                    mPhone.requestFocus();
                }

            }
        }
    });
    mPhone = (EditText) findViewById(R.id.phoneNumber);

    mPhone.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            if(hasFocus){
                //do nothing
            }else{

                if(!Validation.isPhoneNumber(mPhone, true)){
                    mPhone.setError("wrong email");
                    mPhone.requestFocus();
                }else{
                    mPhone.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
                    mPhone.clearFocus();


                }

            }

        }
    });

        mButton = (Button) findViewById(R.id.SubmitRegisterButton);
        mButton.setOnClickListener(this);
    }


    private void submitForm() {
        // Submit your form here. your form is valid
        Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
    }

    private boolean checkValidation() {
        boolean ret = true;

        if (!Validation.hasText(mFullName)){
            ret = false;

        }

        if (!Validation.isEmailAddress(mEmail, true)){
            ret = false;
        }

        if (!Validation.isPhoneNumber(mPhone, true)){
            ret = false;
        }

        if (!Validation.hasText(mPhone)){

            ret = false;

        }

        return ret;
    }//checkValidation


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub


        if ( checkValidation () ){
            submitForm();
            Intent i = new Intent(getApplicationContext(), ThanksZuser.class);
            startActivity(i);
            finish();
            //send to our crm
            grabURL(myURL);
        }else
            Toast.makeText(ConTct.this, "Form contains error", Toast.LENGTH_LONG).show();
    }
}//ConTct.class

验证类:

package com.Signals4Trading.push.android;

import java.util.regex.Pattern;

import android.widget.EditText;

public class Validation {

    // Regular Expression
    // you can change the expression based on your need
    private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    //  private static final String PHONE_REGEX = "\\d{3}-\\d{7}";
    //  private static final String PHONE_REGEX = "(\\d{3})-(\\d{3})-(\\d{4})";
    private static final String PHONE_REGEX = "([0-9-( )]+)";


    // Error Messages
    private static final String REQUIRED_MSG = "Invalid name. You have to input at least 3 characters";
    private static final String EMAIL_MSG = "Invalid email";
    private static final String PHONE_MSG = "Invalid number";

    // call this method when you need to check email validation
    public static boolean isEmailAddress(EditText editText, boolean required) {
        return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
    }

    // call this method when you need to check phone number validation
    public static boolean isPhoneNumber(EditText editText, boolean required) {
        return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
    }

    /*
    // return true if the input field is valid, based on the parameter passed
    public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {

        String text = editText.getText().toString().trim();
        // clearing the error, if it was previously set by some other values
        editText.setError(null);

        // text required and editText is blank, so return false
        if ( required && !hasText(editText) ) return false;

        // pattern doesn't match so returning false
        if (required && !Pattern.matches(regex, text)) {
            editText.setError(errMsg);
            return false;
        };

        if ( required && !hasNumber(editText)) return false;

        return true;
    }
     */

    // return true if the input field is valid, based on the parameter passed
    public static boolean isValid(EditText editText, String regex, String errMsg, boolean bRequired) {
        // text required and editText is blank, so return false
        String sText = editText.getText().toString().trim();
        // clearing the error, if it was previously set by some other values
        editText.setError(null);
        if (sText.length() == 0) {
            if (bRequired) {
                editText.setError("*Field required");
                return false;
            }
        } else {
            // filled field
            // pattern doesn’t match so returning false
            if (!Pattern.matches(regex, sText)) {
                editText.setError(errMsg);
                return false;
            }
        }
        return true;
    }

    // check the input field has any text or not
    // return true if it contains text otherwise false
    public static boolean hasText(EditText editText) {

        String text = editText.getText().toString().trim();
        editText.setError(null);

        // length less that 3 means there is no text
        if (text.length() <= 3 && text.length() > 12) {
            editText.setError(REQUIRED_MSG);
            return false;
        }

        return true;
    }

    public static boolean hasNumber(EditText editText) {

        String text = editText.getText().toString().trim();
        editText.setError(null);

        // length less that 6 and more than 11 means not available
        if (text.length() <= 6 && text.length() >= 11) {
            editText.setError(PHONE_MSG);
            return false;
        }

        return true;
    }

}//Validation

1 个答案:

答案 0 :(得分:1)

  

我的主要问题是我只能输入1个字符,然后它会显示我或   错误或选中的图标,它会转到下一个字段。

问题是:

您正在onTextChanged中调用验证方法。所以它进入hasText方法,确定少于3个字符,并显示错误。在您的情况下,最好使用OnFocusChangeListener

来实现

示例:

myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus){
            //do nothing
        }else {
            // validate here and show error if invalid and set focus to this element again using requestFocus.
        }
    }
});

希望这有帮助。