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

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

    Due to goto10's observation, I put together the following code to protected against loosing other filters with setting the max length:

    /**
     * This sets the maximum length in characters of an EditText view. Since the
     * max length must be done with a filter, this method gets the current
     * filters. If there is already a length filter in the view, it will replace
     * it, otherwise, it will add the max length filter preserving the other
     * 
     * @param view
     * @param length
     */
    public static void setMaxLength(EditText view, int length) {
        InputFilter curFilters[];
        InputFilter.LengthFilter lengthFilter;
        int idx;
    
        lengthFilter = new InputFilter.LengthFilter(length);
    
        curFilters = view.getFilters();
        if (curFilters != null) {
            for (idx = 0; idx < curFilters.length; idx++) {
                if (curFilters[idx] instanceof InputFilter.LengthFilter) {
                    curFilters[idx] = lengthFilter;
                    return;
                }
            }
    
            // since the length filter was not part of the list, but
            // there are filters, then add the length filter
            InputFilter newFilters[] = new InputFilter[curFilters.length + 1];
            System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length);
            newFilters[curFilters.length] = lengthFilter;
            view.setFilters(newFilters);
        } else {
            view.setFilters(new InputFilter[] { lengthFilter });
        }
    }
    

提交回复
热议问题