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

后端 未结 22 2180
囚心锁ツ
囚心锁ツ 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条回答
  •  被撕碎了的回忆
    2020-11-22 14:27

    I have had this problem and I consider we are missing a well explained way of doing this programmatically without losing the already set filters.

    Setting the length in XML:

    As the accepted answer states correctly, if you want to define a fixed length to an EditText which you won't change further in the future just define in your EditText XML:

    android:maxLength="10"     
    

    Setting the length programmatically

    To set the length programmatically you'll need to set it through an InputFilter. But if you create a new InputFilter and set it to the EditText you will lose all the other already defined filters (e.g. maxLines, inputType, etc) which you might have added either through XML or programatically.

    So this is WRONG:

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

    To avoid losing previously added filters you need to get those filters, add the new one (maxLength in this case), and set the filters back to the EditText as follow:

    Java

    InputFilter[] editFilters = editText.getFilters();
    InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
    System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
    newFilters[editFilters.length] = new InputFilter.LengthFilter(maxLength); 
    editText.setFilters(newFilters);
    

    Kotlin however made it easier for everyone, you also need to add the filter to the already existing ones but you can achieve that with a simple:

    editText.filters += InputFilter.LengthFilter(maxLength)
    

提交回复
热议问题