Home » Android » android – Prevent user from inserting more characters after size limit is reached in EditText box

android – Prevent user from inserting more characters after size limit is reached in EditText box

Posted by: admin June 16, 2020 Leave a comment


I want to prevent the user from inserting more letters than a certain amount to an alert dialog that contain an Edit-text instance. I try to use Input filter. Length Filter, but that only displays the string up to the requested length. The user can still write more characters, and when I try to delete characters for example, nothing happens until I delete enough characters for the word to be shorter than the limit (the like keyboard remembers the keys).

To be more clear, I’ve already tried using InputFilter. That indeed enforces a string size that is passed to the EditText, but as I said I can still continue to write letters with the keyboard which are not displayed in the text box. When I hit delete, it deletes the extra letters first and only after enough letters have been deleted, I start to see the letters in the text box deleting. My requested scenario: set the string limit to 10. Hit 15 characters in my keyboard. Then hit backspace and see the last letter in the text box get deleted.
I hope this is more clear now.

Can someone help?

How to&Answers:

You can use following propery of EditText in AndroidManifest.xml


Now user can not add more than 8 characters in the EditText.


Probably it’s to late but if someone have the same problem.

In layout:



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


You can set this property also at runtime by assigning


You told that you have your edit-text inside alert dialog box so set this at runtime and give a try.



TextView editEntryView = new TextView(...);
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(8);


See this answer for a partial workaround: https://stackoverflow.com/a/19222238/933656

You will be able to immediately delete the last character in the EditText because there is no preview for the keyboard to show (assuming all third-party keyboards respect the textNoSuggestions flag). The only problem is that you lose the suggestion text.