基本上我想了解更深入的差异和使用场景InputFilter
and TextWatcher
.
根据文档:
InputFilter
:输入过滤器可以附加到可编辑项以限制可以对其进行的更改。
TextWatcher
:当某个类型的对象附加到可编辑对象时,当文本更改时将调用其方法。因此,如果我错了,它可以用来约束更改纠正我
哪一个更好?为什么?我的情况是我需要一个小数点后至少有 6 个字符的 EditText。
TextWatcher
用于在用户键入时收到通知。
InputFilter
决定可以输入什么内容。
例如,
假设我想让用户输入温度。该温度必须全部是数字,并且只能包含小数点后两位数字。如果你仔细看,我两个都需要TextWatcher
and 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)