My idea is to set an error View
to the EditText
when the maximum character limit has been reached. Is there any callback about this event, or may be there's another way to achieve this effect? Thanks in advance.
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 http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/text/InputFilter.java#InputFilter.LengthFilter.filter%28java.lang.CharSequence%2Cint%2Cint%2Candroid.text.Spanned%2Cint%2Cint%29 )
you can 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
editText.setError("Overflow");
}
return res;
}
}
});
You can use the edit text's setError
:
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
if(s.length() > max)
editText.setError("Error");
}
});
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