您的位置:首页 > 编程语言

代码中设置edittext的长度

2014-05-22 17:19 218 查看
代码中我们设置最大输入长度的方法:

editText.setFilters(
new InputFilter[]{ new InputFilter.LengthFilter( 100 )});

所以可以使用一下方法获得可输入的最大长度:

1. 通过editText.getFilters()获得Filters数组

2. 通过instanceof方法找到类InputFilter.LengthFilter的实例filter

3. 翻看源码:

/**

* This filter will constrain edits not to make the length of the text

* greater than the specified length.

*/

public static class LengthFilter implements InputFilter {

public LengthFilter(int max) {

mMax = max;

}

public CharSequence filter(CharSequence source, int start, int end,

Spanned dest, int dstart, int dend) {

int keep = mMax - (dest.length() - (dend - dstart));

if (keep <= 0) {

return "";

} else if (keep >= end - start) {

return null; // keep original

} else {

keep += start;

if (Character.isHighSurrogate(source.charAt(keep - 1))) {

--keep;

if (keep == start) {

return "";

}

}

return source.subSequence(start, keep);

}

}

private int mMax;

}

可以看到系统没有提供获得mMax的API,所以只用通过反射的方式来会的mMax

至此,最大可输入长度就获得了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: