Android: checking EditText with TextWatcher and .setError ()

I implemented a simple check for TextEdit using this code:

    title = (EditText) findViewById(R.id.title);
    title.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
             if (title.getText().length() < 1) {
                    title.setError( "Title is required" );
               } else {
                    title.setError(null); 
               }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }
    });

The funcion function checks to see if there is any text inserted in the text exchange, and everything works fine, unless I put the cursor in the already empty header field and click Delete again. the error message will be discarded and the text element will not be called because there is no text change. How can I even display an error message in this case?

+1
source share
2 answers

onKeyUp (http://developer.android.com/reference/android/view/KeyEvent.Callback.html). , KeyEvent.KEYCODE_DEL, , EditText . , .

0

, TextView setError(null), , . EditText onKeyPreIme(), , "". EditTextErrorFixed XML :

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

All Articles