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

后端 未结 22 1864
囚心锁ツ
囚心锁ツ 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:24

    Xml

    android:maxLength="10"
    

    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:

    editText.filters += InputFilter.LengthFilter(maxLength)
    

提交回复
热议问题