且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

***实践:输入验证(Android)

更新时间:2023-02-26 18:44:02

这个java类实现了一个 TextWatcher 来看 您的编辑文本,观看对文本所做的任何更改:

This java class implements a TextWatcher to "watch" your edit text, watching any changes done to the text:

public abstract class TextValidator implements TextWatcher {
    private final TextView textView;

    public TextValidator(TextView textView) {
        this.textView = textView;
    }

    public abstract void validate(TextView textView, String text);

    @Override
    final public void afterTextChanged(Editable s) {
        String text = textView.getText().toString();
        validate(textView, text);
    }

    @Override
    final public void 
    beforeTextChanged(CharSequence s, int start, int count, int after) {
         /* Needs to be implemented, but we are not using it. */ 
    }

    @Override
    final public void 
    onTextChanged(CharSequence s, int start, int before, int count) { 
         /* Needs to be implemented, but we are not using it. */    
    }
}

并在中EditText ,您可以将该文本观察者设置为其监听器

And in your EditText, you can set that text watcher to its listener

editText.addTextChangedListener(new TextValidator(editText) {
    @Override public void validate(TextView textView, String text) {
       /* Insert your validation rules here */
    }
});