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

后端 未结 22 2100
囚心锁ツ
囚心锁ツ 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"

    Programmatically:

    int maxLength = 10;
    InputFilter[] filters = new InputFilter[1];
    filters[0] = new InputFilter.LengthFilter(maxLength);
    yourEditText.setFilters(filters);
    

    Note: internally, EditText & TextView parse the value of android:maxLength in XML and use InputFilter.LengthFilter() to apply it.

    See: TextView.java#L1564

提交回复
热议问题