基本上,我想更深入地了解 InputFilter
和 TextWatcher
的区别和使用场景。
根据文档:
InputFilter
:InputFilters 可以附加到 Editables 以限制可以对其进行的更改。
TextWatcher
:当一个类型的对象附加到一个 Editable 时,当文本发生变化时将调用它的方法。 所以它可以用来约束变化如果我错了请纠正我
哪个更好?为什么?我的情况是我需要一个小数点后至少有 6 个字符的 EditText。
最佳答案
TextWatcher
用于在用户输入时收到通知。
InputFilter
决定可以输入的内容。
例如,
假设我想让用户输入温度。这个温度必须是所有数字,并且只能包含小数点后两位数。如果仔细观察,我需要 TextWatcher
和 InputFilter
。
InputFilter
将只允许数字。
final InputFilter[] filters = new InputFilter[]
{ DigitsKeyListener.getInstance(true, true) };
textView.setFilters(filters);
现在,这将允许小数点后两位数以上的数字。为什么?因为 InputFilter
只限制可以输入的键。这是 TextWatcher
进来的时候。
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// you need this to avoid loops
// or your stack will overflow
if(!textView.hasWindowFocus() || textView.hasFocus() || s == null){
return;
}
// Now you can do some regex magic here to see
// if the user has entered a valid string
// "\\d+.\\d{6,}" for your case
}
关于Android EditText 结合 InputFilter vs TextWatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33855769/