Android EditText 结合 InputFilter vs TextWatcher [英] Android EditText combined with InputFilter vs TextWatcher

查看:52
本文介绍了Android EditText 结合 InputFilter vs TextWatcher的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想了解更多 InputFilterTextWatcher 的深度差异和使用场景.

Basically I would like to know more in depth difference and usage scenario for InputFilter and TextWatcher.

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

As per the docs:
InputFilter: InputFilters can be attached to Editables to constrain the changes that can be made to them.

TextWatcher: 当一个类型的对象附加到一个 Editable 时,它​​的方法将在文本改变时被调用.所以它可以用来约束更改,如果我错了,请纠正我

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

Which one is better? and why? My scenario is I need an EditText with minimum 6 characters after decimal point in it.

推荐答案

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

TextWatcher is used to be notified whenever user types.
InputFilter decides what can be typed.

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

InputFilter 将只允许数字.

final InputFilter[] filters = new InputFilter[]
                { DigitsKeyListener.getInstance(true, true) };
textView.setFilters(filters);   

现在,这将允许小数点后超过两位数的数字.为什么?因为 InputFilter 只限制可以输入的键.这是 TextWatcher 进来的时候.

Now, this would allow numbers with more than two digits after decimal. Why? Because InputFilter only restricts what keys can be typed. Here's when TextWatcher comes in.

@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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆