pokoso pokoso - 4 months ago 70
Android Question

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

Answer

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


    }