我建议验证用户的输入有TextWatcher:
EditText textbox = new EditText(context);
textbox.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// Your validation code goes here
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
只处理验证在afterTextChanged方法,不要接触其他两个,如documentation建议。然而,afterTextChanged被触发后,每当输入改变,所以如果用户输入单词“hello”,这个方法在输入h时被调用,然后当输入e时再次调用等等。此外,如果修改edittext值在afterTextChanged中,方法get也被调用。
另一种方法是在EditText失去焦点时验证用户输入。为了这个目的,你可以使用:
textbox.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// Your validation code goes here
}
});
但是要小心,有些部件可能不会抢焦点,所以你EDITTEXT从来没有失去它(有与按钮实例)。
此外,EditText上提供setError方法,这标志着一个红色的错误标记的EditText并显示传递给SETERROR给用户(该文本可以通过你的呼唤SETERROR(“你的错误信息”时可以设置))文本。