Android: EditText Validation with TextWatcher and .setError()

前端 未结 2 1473
情话喂你
情话喂你 2020-12-10 23:39

i have implemented a simple validation for an TextEdit, using this code:

    title = (EditText) findViewById(R.id.title);
    title.addTextChangedListener(ne         


        
相关标签:
2条回答
  • 2020-12-10 23:46

    It seems that internally TextView has a flag and calls setError(null) if the keyboard sends a key command but the text remains the same. So I subclassed EditText and implemented onKeyPreIme() to swallow the delete key if the text is "". Just use EditTextErrorFixed in your XML files:

    package android.widget;
    
    import android.content.Context;
    import android.text.TextUtils;
    import android.util.AttributeSet;
    import android.view.KeyEvent;
    
    public class EditTextErrorFixed extends EditText {
        public EditTextErrorFixed(Context context) {
            super(context);
        }
    
        public EditTextErrorFixed(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public EditTextErrorFixed(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        /**
         * Don't send delete key so edit text doesn't capture it and close error
         */
        @Override
        public boolean onKeyPreIme(int keyCode, KeyEvent event) {
            if (TextUtils.isEmpty(getText().toString()) && keyCode == KeyEvent.KEYCODE_DEL)
                return true;
            else
                return super.onKeyPreIme(keyCode, event);
        }
    }
    
    0 讨论(0)
  • 2020-12-11 00:01

    You should be able to also override the onKeyUp method (http://developer.android.com/reference/android/view/KeyEvent.Callback.html). In there, check to see if the key pressed was KeyEvent.KEYCODE_DEL, then also check to see if the text in the EditText is empty. If it is, throw your error.

    0 讨论(0)
提交回复
热议问题