在Android中限制EditText文本长度的最佳方法是什么?

有没有通过xml实现这一点的方法?


当前回答

XML

android:maxLength=“10”

编程方式:

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

注意:在内部,EditText和TextView解析XML中android:maxLength的值,并使用InputFilter.LengthFilter()应用它。

参见:TextView.java#L1564

其他回答

以编程方式为Java尝试以下操作:

myEditText(new InputFilter[] {new InputFilter.LengthFilter(CUSTOM_MAX_LEN)});
TextView tv = new TextView(this);
tv.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(250) });

由于goto10的观察,我将以下代码组合在一起,通过设置最大长度来防止丢失其他过滤器:

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

对于已经使用自定义输入筛选器并希望限制最大长度的用户,请注意:

当您在代码中分配输入过滤器时,所有先前设置的输入过滤器都将被清除,包括一个使用android:maxLength设置的过滤器。我在尝试使用自定义输入筛选器以防止在密码字段中使用某些不允许的字符时发现了这一点。使用setFilters设置过滤器后,不再观察到maxLength。解决方案是以编程方式将maxLength和自定义过滤器设置在一起。类似于:

myEditText.setFilters(new InputFilter[] {
        new PasswordCharFilter(), new InputFilter.LengthFilter(20)
});

您可以在EditText中使用android:maxLength=“10”。(此处限制为最多10个字符)