Reputation: 21637
After I set the max character limit for an editText using InputFilter.LengthFilter, is there a way to make editText to react at onTextChanged after it reaches the maximum number of characters? if not, is there a simple way to set a max number of characters to an editText and still react at onTextChanged event?
Upvotes: 5
Views: 11202
Reputation: 5999
In XML itself for EditText give the following Attrib,
android:maxLength="20"
Upvotes: 12
Reputation: 6781
I was going through the same problem and some research on SO got me this solution. Thanks to @njzk2 for the brilliant solution. Posting it here so others can get the answer.
maxLength
attribute in the EditText
is actually an InputFilter
, which you can write yourself and supply from code.
You can look at the implementation of InputFilter.LengthFilter, which basically returns null
if there is no overflow. (see link)
WIth a little modification to that : create an extension to InputFilter.LengthFilter
in which you call super
and compare it to null
to decide if you need to display an alert.
editText.setInputFilters(new InputFilter[] {
new InputFilter.LengthFilter(max) {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
CharSequence res = super.filter(source, start, end, dest, dstart, dend);
if (res != null) { // Overflow
Toast.makeText(this,"OVERFLOW!",Toast.LENGTH_SHORT).show();
}
return res;
}
}
});
Upvotes: 0