更新时间:2023-10-16 18:41:16
为进一步说明Prithviraj给出的答案,TextInputLayout
本身不会进行验证.它只是一种显示错误或提示的机制.您负责设置/清除错误.这是您可以执行的操作.请注意,除了TextChangedListener之外,您可能还需要OnFocusChangeListener来设置当用户跳至第二个编辑文本而未在第一个字段中进行任何修改时设置的错误.
To illustrate further the answer given by Prithviraj, TextInputLayout
does not do the validation itself. It is just a mechanism to show the error or hint. You are responsible for setting/clearing the error. Here is how you can do that. Note that in addition to TextChangedListener, you may also need OnFocusChangeListener to set the error when user jumps to second edit text without doing any modification in the first field.
protected void onCreate(Bundle savedInstanceState) {
//.....
edtPhone.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
validateEditText(s);
}
});
edtPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
validateEditText(((EditText) v).getText());
}
}
});
}
private void validateEditText(Editable s) {
if (!TextUtils.isEmpty(s)) {
layoutEdtPhone.setError(null);
}
else{
layoutEdtPhone.setError(getString(R.string.ui_no_password_toast));
}
}
}