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

后端 未结 22 2105
囚心锁ツ
囚心锁ツ 2020-11-22 13:33

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

Is there a way to do this via xml?

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 14:37

    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)
    });
    

提交回复
热议问题