It is possible to add filters in Android by doing something like this to add a 3 char limit to the field:
editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(3) });
What about removing an already set filter though? My problem is I will be switching between a 3 and 4 character max length on the field depending on a selection by the user. Just running the above code feels like it would generate alot of extra work for the GC.
I could of course add a couple of instance variables that correspond to each filter and just add them when needed and then I would only have the two filters which is fine for this case. It would be interesting to know if it is possible to completely remove a filter though. Perhaps by passing in null?
If you do want to just remove filters, rather than replace one with another, you can do it with
editText.setFilters(new InputFilter[] {});
If you want to replace a precise Filter (to change its configuration for example, but without touching the others), you can filter the list based on its class :
val filters = editText.filters.toList().filter { it.javaClass != InputFilter.LengthFilter::class.java } // remove the older filter
editText.filters = filters.toTypedArray() + InputFilter.LengthFilter(maxLength) // set the new one
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