问题描述
我已经使用以下代码对 TextEdit
实现了一个简单的验证:
I have implemented a simple validation for a 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
}
});
该函数检查 textchange
上是否插入了任何文本,并且一切正常,直到我将光标放在已经为空的标题字段中,然后再次按删除.错误消息被重置并且 textwatcher
未被调用,因为没有文本更改.在这种情况下,我什至如何显示错误消息?
The function checks if there is any text inserted on a textchange
and everything works perfectly, until I put my cursor in the already empty title field, and press delete once more. the error message gets reset and the textwatcher
is not called, because there is no text change. How can I even display the error message in this case?
推荐答案
查看最新的 textInputLayout 和 textInputEditText 以获得更好的结果-https://material.io/components/text-fields/android
Check the latest textInputLayout and textInputEditText for better results-https://material.io/components/text-fields/android
这篇关于Android:使用 TextWatcher 和 .setError() 进行 EditText 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!