Android EditText combined with InputFilter vs TextWatcher

Basically I would like to know more about the difference in depth and usage scenarios for InputFilterand TextWatcher.

According to docs::
InputFilterInputFilters can be attached to Editables to limit the changes that can be made to them.

TextWatcher: When a type object is attached to an editable one, its methods will be called when the text changes. So it can be used to limit changes, correct me if I am wrong

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

+4
source share
1 answer

TextWatcherused for notification every time types are used.
InputFilterdecides what can be entered.

For example,
suppose I want the user to enter a temperature. This temperature should be all numbers and can contain only two digits after the decimal. If you look closely, I need both TextWatcher, and InputFilter.

InputFilter allows only numbers.

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

This will now allow numbers with more than two digits after the decimal number. What for? Because it InputFilterlimits only what keys can be entered. Here when TextWatcherit 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

}
+8
source

Source: https://habr.com/ru/post/1616943/


All Articles