Android:: Set max-length of EditText programmatically with other InputFilter

Just try this way

InputFilter

InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; ++i)
            {
                if (!Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890]*").matcher(String.valueOf(source.charAt(i))).matches())
                {
                    return "";
                }
            }

            return null;
        }
    };

How to apply

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText edt =(EditText)findViewById(R.id.edt) ;

        edt.setFilters(new InputFilter[]{filter,new InputFilter.LengthFilter(10)});


    }

public void setEditTextMaxLength(int length) {
    InputFilter[] filterArray = new InputFilter[1];
    filterArray[0] = new InputFilter.LengthFilter(length);
    edt_text.setFilters(filterArray);
}

A simple one-liner would be:

myEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) });

//replace 10 with required length.

Tags:

Android