代码中我们设置最大输入长度的方法:
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
至此,最大可输入长度就获得了。
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
至此,最大可输入长度就获得了。