由于EditText的官方方法中只能设置它的最大输入长度,所以我们如果要设置它的最大字符数的话,虽然可以采用监听EditText的变化事件,动态计算输入的字符数实现,但是在实现的过程中发现比较麻烦 而且用户体验也不是很好,以下是我仿照官方在代码中实现最大输入字数写的一个限制输入字符数的功能
InputFilter[] filters = new InputFilter[] { new LimitCharLengthFilter(12) };
editText.setFilters(filters);
/**
* 限制输入的字符的数量
*
* @author wjh
*
*/
public class LimitCharLengthFilter implements InputFilter
{
private int mMax = 0;
public LimitCharLengthFilter(int mMax)
{
super();
this.mMax = mMax;
}
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend)
{
int bytes = 0;
int sourceBytes = 0;
int keep = 0;
try
{
bytes = dest.toString().getBytes("GBK").length;
sourceBytes = source.toString().getBytes("GBK").length;
if (bytes + sourceBytes <= mMax)
{
keep = source.length();
} else
{
for (int i = 0; i < source.length(); i++)
{
int currentSoureBytes = source.subSequence(0, i + 1)
.toString().getBytes("GBK").length;
if (bytes + currentSoureBytes > mMax)
{
keep = i;
break;
}
}
}
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if (keep <= 0)
{
return "";
}
return source.subSequence(start, keep + start);
}
}