What's the best way to limit text length of EditText in Android

What's the best way to limit the text length of an EditText in Android?

Is there a way to do this via xml?


Solution 1:

Documentation

Example

android:maxLength="10"

Solution 2:

use an input filter to limit the max length of a text view.

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

Solution 3:

EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});

Solution 4:

A note to people who are already using a custom input filter and also want to limit the max length:

When you assign input filters in code all previously set input filters are cleared, including one set with android:maxLength. I found this out when attempting to use a custom input filter to prevent the use of some characters that we don't allow in a password field. After setting that filter with setFilters the maxLength was no longer observed. The solution was to set maxLength and my custom filter together programmatically. Something like this:

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