Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android EditText combined with InputFilter vs TextWatcher

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

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

TextWatcher: When an object of a type is attached to an Editable, its methods will be called when the text is changed. So it can be used to constrain the change correct me if I am wrong

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

like image 321
Shadow Droid Avatar asked Nov 22 '15 14:11

Shadow Droid


People also ask

What is the use of TextWatcher in Android?

EditText is used for entering and modifying text. While using EditText width, we must specify its input type in inputType property of EditText which configures the keyboard according to input. EditText uses TextWatcher interface to watch change made over EditText.

In which condition is TextWatcher used?

The TextWatcher interface can be used for listening in for changes in text in an EditText.

What is the use of input filter?

Stay organized with collections Save and categorize content based on your preferences. InputFilters can be attached to Editable s to constrain the changes that can be made to them.


1 Answers

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

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

InputFilter would allow only numbers.

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

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

}
like image 71
An SO User Avatar answered Sep 20 '22 12:09

An SO User