Android EditText 结合 InputFilter vs TextWatcher

标签 android performance

基本上,我想更深入地了解 InputFilterTextWatcher 的区别和使用场景。

根据文档:
InputFilter:InputFilters 可以附加到 Editables 以限制可以对其进行的更改。

TextWatcher:当一个类型的对象附加到一个 Editable 时,当文本发生变化时将调用它的方法。 所以它可以用来约束变化如果我错了请纠正我

哪个更好?为什么?我的情况是我需要一个小数点后至少有 6 个字符的 EditText。

最佳答案

TextWatcher 用于在用户输入时收到通知。
InputFilter 决定可以输入的内容。

例如,
假设我想让用户输入温度。这个温度必须是所有数字,并且只能包含小数点后两位数。如果仔细观察,我需要 TextWatcherInputFilter

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/

相关文章:

c - 如何显示合并排序的时间性能?

oracle - 有没有办法保证 PL/SQL 作业的 DAP?

android - android录音音量变化

android - 为 AlarmManager 警报创建 Wi-Fi 唤醒锁

performance - Jmeter中的多个VU-只有一个用户能够插入数据

javascript - 奇数的完美平方

PHP SQLSRV 在 sqlsrv_fetch_array/sqlsrv_fetch 上有间歇性延迟

java - 如何在编辑文本聚焦时显示软键盘

java - 如何在android中的另一个imageview上半重叠imageview

android - APP URI for app Indexing an android app