代码中设置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
至此,最大可输入长度就获得了。
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在代码中设置最大输入长度并设置为密码输入框
- EditText在代码中设置最大输入长度并设置为密码输入框
- 如何在代码中设置 edittext 的长度.
- 代码设置Android EditText的相关问题。输入长度maxLength
- 如何在代码中设置以dp为单位的长度
- 代码设置EditText 长度
- EditText---android 中EditText加入图标 更改边框颜色 设置透明 代码 .
- 在代码在设置EditText
- Android 在java代码中设置EditText只接受数字输入
- 一行代码设置UITableView分割线的长度
- 修改sts设置代码每行长度
- Android 在java代码中设置EditText只接受数字输入
- JTextField设置最大长度的小代码
- EditText的InputType属性,可以在代码中设置,也可以预先在xml中定义对应关系
- android 中 EditText加入图标 更改边框颜色 设置透明 代码
- 设置 ProgressBar 进度条(条形) 的颜色和用代码动态控制显示的长度
- android 中 EditText加入图标 更改边框颜色 设置透明 代码
- EditText在Java代码中设置只读的方法
- android EditText 控件无法代码设置ReadOnly 只读
- 设置格式代码换行长度