addTextChangedListener无法在marshmallow上运行

时间:2016-10-04 10:57:42

标签: android

当我使用(MY EditText).addTextChangedListener而不是它在android 6.0以下的所有设备中工作但不能在android 6.0和更高版本上工作。这是我使用的代码

 email.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            if (!isValidEmail(s.toString())) {
                email.setTextColor(Color.parseColor("#EB2525"));
            } else {
                email.setTextColor(Color.parseColor("#088A08"));
            }
        }
    }); 

请帮帮我。

提前感谢。

2 个答案:

答案 0 :(得分:1)

试试这个对我有帮助。

在oncreate方法中

  inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));

以下是一些代码: -

 private class MyTextWatcher implements TextWatcher {

    private View view;

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

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void afterTextChanged(Editable editable) {
        switch (view.getId()) {
             case R.id.input_email:
                validateEmail();
                break;

        }
    }
}


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

    if (email.isEmpty() || !isValidEmail(email)) {
        inputLayoutEmail.setError(getString(R.string.err_msg_email));
         return false;
    } else {
        inputLayoutEmail.setErrorEnabled(false);
    }

    return true;
}
  private static boolean isValidEmail(String email) {
    return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

答案 1 :(得分:-1)

edt_email.addTextChangedListener( new GenericTextWatcher(edt_email));

private class GenericTextWatcher implements TextWatcher {

    private View view;

    private GenericTextWatcher(View v) {
        this.view = v;
    }

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void afterTextChanged(Editable editable) {

    }
}