安卓的EditText的验证与TextWatcher和.setError()

问题描述:

我实现了一个简单的验证一个文字编辑,使用这个code:

i have implemented a simple validation for an 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

        }
    });

在funcion检查,如果有插在一个textchange任何文字,一切完美的作品,除非当我把我的光标已经空标题域,preSS删除一次。错误信息被重置了和textwatcher不叫,因为没有文字的变化。我怎么能即使在这种情况下显示错误信息?

The funcion checks, if there is any text inserted on a textchange and everything works perfectly, unless when i put my cursor in the already empty title field, and press delete once more. the error message gets resetted and the textwatcher is not called, because there is no text change. How can i even display the error message in this case?

看来,国内的TextView 有一个标志,并调用 SETERROR(空) 如果键盘发送键命令,但文本保持不变。所以我子类的EditText 和实施 onKey $ P $宗座外方传教会()吞了删除键,如果该文本是 。只需使用 EditTextErrorFixed XML文件中的:

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);
    }
}