限制Android中EditText的文本长度

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

有没有办法经过xml作到这一点? 编程


#1楼

一个注谁正在使用一个自定义的输入滤波器, 但愿限制最大长度的人: this

当您在代码中分配输入过滤器时,全部先前设置的输入过滤器都会被清除,包括android:maxLength一组。 在尝试使用自定义输入过滤器以防止使用某些密码字段中不容许的字符时,我发现了这一点。 使用setFilters设置该过滤器后,再也不观察到maxLength。 解决方案是经过编程将maxLength和个人自定义过滤器一块儿设置。 像这样: spa

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

#2楼

因为goto10的观察,我将如下代码放在一块儿,以防止经过设置最大长度而丢失其余过滤器: code

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

#3楼

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

#4楼

EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});

#5楼

实现此目的的另外一种方法是将如下定义添加到XML文件: xml

<EditText
    android:id="@+id/input"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:maxLength="6"
    android:hint="@string/hint_gov"
    android:layout_weight="1"/>

这会将EditText小部件的最大长度限制为6个字符。 get

相关文章
相关标签/搜索