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

I'm using InputFilter like this to allow only alpha and numbers

private InputFilter[] inputFilters = new InputFilter[] { 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;
    }
} };

But problem is "android:maxLength" value in xml file is not working with this InputFilter

I think I need code in InputFilter to set max-length of EditText

Anyone has good idea for this?

Thanks


Solution 1:

A simple one-liner would be:

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

//replace 10 with required length.

Solution 2:

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

Solution 3:

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)});


    }

Solution 4:

For Kotlin

myEditText.filters = arrayOf(InputFilter.LengthFilter(maxLength))