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.
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.
The TextWatcher interface can be used for listening in for changes in text in an EditText.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With