Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText maximum characters limit exceeded callback

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.

like image 662
Egor Avatar asked Dec 04 '22 01:12

Egor


2 Answers

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.

edit - with code

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;
        }
    }
});
like image 178
njzk2 Avatar answered Jan 03 '23 12:01

njzk2


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");
        }
    });
like image 21
Nermeen Avatar answered Jan 03 '23 10:01

Nermeen