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

Questions:

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).

EDIT:
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

android:maxLength="8"

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

Answer:

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

In layout:

android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="20"

Programatically:

setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

Answer:

You can set this property also at runtime by assigning

youredittext.setMaxLength(8);

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

Answer:

SEE THIS

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

Answer:

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.