android EditText maxLength allows user to type more

Unfortunately the following answer does not work. However, it helped us to find out that the bug mentioned by Poly Bug is not reproducible if the input begins with a number.


You can use a TextWatcher to listen for EditText changes and prevent the user from typing too many characters into the field. The following code works for me:

final int maxLength = 10;
EditText editText = (EditText) findViewById(R.id.my_edittext_id);
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() >= maxLength) s.delete(maxLength, s.length());
    }
});

In afterTextChanged, the code compares the length of the inserted text with the maximal length maxLength and deletes all superfluous characters.


You might replace all standard EditText classes with the following class to use the listener in conjunction with the maxLength XML attribute:

public class MyMaxLengthEditText extends EditText {
    public static final String XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android";
    private final int mMaxLength;

    public MyMaxLengthEditText(Context context) {
        super(context, null);
        mMaxLength = -1;
    }

    public MyMaxLengthEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", -1);
        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= mMaxLength) s.delete(mMaxLength, s.length());
            }
        });
    }
}

  1. Disable auto-suggestions(android:inputType="textFilter" or textNoSuggestions):
  2. Set maxLength

    <EditText
       android:id="@+id/editText"
       android:inputType="textFilter"
       android:maxLength="8"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />
    

I hope, it helps