edittext错误无法正确显示

时间:2016-02-16 14:34:37

标签: android android-edittext

我正在尝试在活动中创建的表单中实现验证。 一切正常,但错误未正确显示。 例如:在第一张图片中,电子邮件的错误显示在edittext上方,它应该在“!”下面。标记。 同样对于第二张图像也是如此。

enter image description here

enter image description here

我的xml代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.android.contactus.MainActivityFragment"
    tools:showIn="@layout/activity_main"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textAllCaps="true" />


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:hint="Enter your name"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="E-mail"
        android:textAllCaps="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:id="@+id/email"
        android:hint="Your E-mail address"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Contact Number"
        android:textAllCaps="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:hint="10-digit phone number"
        android:maxLength="10"
        android:id="@+id/phone" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Message"
        android:textAllCaps="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="top"
        android:inputType="textMultiLine"
        android:maxLength="500"
        android:hint="Enter your message here within 500 characters"
        android:id="@+id/message"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/send_btn" />
</LinearLayout>

fragment_code 公共类MainActivityFragment扩展Fragment {

public MainActivityFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_main, container, false);
    nameEditText = (EditText) rootView.findViewById(R.id.name);
    emailEditText = (EditText) rootView.findViewById(R.id.email);
    phoneEditText = (EditText) rootView.findViewById(R.id.phone);
    messageEditText = (EditText) rootView.findViewById(R.id.message);

    nameEditText.addTextChangedListener(new MyTextWatcher(nameEditText));
    emailEditText.addTextChangedListener(new MyTextWatcher(emailEditText));
    phoneEditText.addTextChangedListener(new MyTextWatcher(phoneEditText));
    messageEditText.addTextChangedListener(new MyTextWatcher(messageEditText));

    send_btn = (Button) rootView.findViewById(R.id.send_btn);
    send_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            submit();
        }
    });
    return rootView;
}

private void submit(){

    if(validateName() && validateEmail() && validatePhone() && validateMessage()){
        createUrlAndSend();
    }
    return;
}

private class MyTextWatcher implements TextWatcher{
    private View view;

    private MyTextWatcher(View view){
        this.view = view;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        switch (view.getId()){
            case R.id.name:
                validateName();
                break;
            case R.id.email:
                validateEmail();
                break;

            case R.id.phone:
                validatePhone();
                break;

            case R.id.message:
                validateMessage();
                break;
        }
    }
}

private boolean validateName() {
    if (nameEditText.getText().toString().isEmpty()) {
        nameEditText.setError("Name could not be empty");
        nameEditText.requestFocus();
        return false;
    }
    return true;
}

private boolean validateEmail(){
    String email = emailEditText.getText().toString().trim();

    if(email.isEmpty() | !isValidEmail(email)){
        emailEditText.setError("Invalid E-mail");
        emailEditText.requestFocus();
        return false;
    }
    return true;
}

private boolean validatePhone(){
    String phone = phoneEditText.getText().toString().trim();

    if(phone.isEmpty()){
        phoneEditText.setError("Field cannot be empty");
        phoneEditText.requestFocus();
        return false;

    }else if(phone.length() < 10 ){
        phoneEditText.setError("Enter 10-digit phone number");
        phoneEditText.requestFocus();
        return false;
    }
    return true;
}

private boolean validateMessage(){
    String message = messageEditText.getText().toString().trim();

    if(message.isEmpty()){
        messageEditText.setError("Field cannot be empty");
        messageEditText.requestFocus();
        return false;
    }
    return true;
}


private void createUrlAndSend(){
    try {
        urlParams = URLEncoder.encode("name", "UTF-8") + "="
                + URLEncoder.encode(nameEditText.getText().toString(), "UTF-8");
        urlParams += "&" + URLEncoder.encode("email","UTF-8") + "="
                + URLEncoder.encode(emailEditText.getText().toString(), "UTF-8");
        urlParams += "&" + URLEncoder.encode("phone","UTF-8") + "="
                + URLEncoder.encode(phoneEditText.getText().toString(), "UTF-8");
        urlParams +=  "&" + URLEncoder.encode("message","UTF-8") + "="
                + URLEncoder.encode(messageEditText.getText().toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        Log.e(LOG_TAG,"error in urlparam");
    }
    //progressDialog.show(context, "", "Loading",false);
    new sendData().execute(urlParams);
}

// validating email id
private boolean isValidEmail(String email) {
    String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

private class sendData extends AsyncTask<String, Void, Void> {

    @Override
    protected void onPreExecute() {
        //progressDialog.show(/* */, "", "Loading",false);
    }

    @Override
    protected Void doInBackground(String... arg) {

        URL url;
        HttpURLConnection httpURLConnection = null;

        try{
            url = new URL(targetUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(
                    httpURLConnection.getOutputStream ());
            wr.writeBytes(urlParams);
            wr.flush();
            wr.close();

            //Get Response
            int responseCode = httpURLConnection.getResponseCode();
            InputStream is = httpURLConnection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;

            StringBuffer response = new StringBuffer();
            while((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            Log.v(LOG_TAG,"response code : " + responseCode);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(httpURLConnection != null){
                httpURLConnection.disconnect();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        Toast.makeText(getActivity(), "Data sent!!", Toast.LENGTH_SHORT).show();
    }
}

}

2 个答案:

答案 0 :(得分:0)

使用SetError Method.and单独验证。使用requestFocus。

       String email = mEmail_signup.getText().toString().trim();
       String password = muser_password.getText().toString().trim();
                boolean cancel = false;
                mEmail_signup.setError(null);
muser_password.setError(null);
            View focusView = null;
            View focusView2 = null;

 if (TextUtils.isEmpty(password)) {
                 muser_password.setError(getString(R.string.error_field_required));
                focusView = muser_password;
                cancel = true;
            }else if(password.length>10)
{
 focusView = muser_password
                cancel = true;
                 muser_password.setError(getString(R.string.error_field_digits));

}
             if (TextUtils.isEmpty(email)) {
                            mEmail_signup.setError(getString(R.string.error_field_required));
                            focusView2 = mEmail_signup;
                            cancel = true;
                        }
                        if (!isEmailValid(email)) {
                            mEmail_signup.setError(getString(R.string.error_invalid_email));
                            focusView2 = mEmail_signup;
                            cancel = true;
                        }

                  if (cancel) {
                    // There was an error; don't attempt login and focus the first
                    // form field with an error.
     if (focusView != null) {
                        focusView.requestFocus();
                    }

                    if (focusView2 != null) {
                        focusView2.requestFocus();
                    }

                } else {
       hideKeyboard();
    callforregister();
              }

答案 1 :(得分:0)

试试这个:

    boolean cancel = false;
    View focusView = null;

    // Reset errors.
    nameEditText.setError(null);
    emailEditText.setError(null);

    // Store values
    name = nameEditText.getText().toString();
    email = emailEditText.getText().toString();




    if (!Validator.isEmpty(nameEditText)) {
        nameEditText
                .setError(getString(R.string.error_field_must_not_be_empty));
        focusView = nameEditText;
        cancel = true;
    }


    if (!Validator.isEmpty(emailEditText)) {
        emailEditText
                .setError(getString(R.string.error_field_must_not_be_empty));
        focusView = emailEditText;
        cancel = true;
    }



    if (cancel) {
        // There was an error; 
        focusView.requestFocus();
    } else {
        //do your code here
    }