限制EditText的输入字数

    private EditText edit_student_name;
  edit_student_name.addTextChangedListener(changeStudentNameWatcher);


private TextWatcher changeStudentNameWatcher = new TextWatcher() {
private int editStart ;
private int editEnd ;
public void afterTextChanged(Editable s) {

edit_student_name.setSelection(edit_student_name.length());
editStart = edit_student_name.getSelectionStart();
editEnd = edit_student_name.getSelectionEnd();
// 先去掉监听器,否则会出现栈溢出
edit_student_name
.removeTextChangedListener(changeStudentNameWatcher);
// 注意这里只能每次都对整个EditText的内容求长度,不能对删除的单个字符求长度
// 因为是中英文混合,单个字符而言,calculateLength函数会返回1或2
long calculateLength = CalculateStringLength(s.toString());
if (calculateLength > MAX_NAME_COUNT_CLASSNAME ) {
Toast. makeText(getApplicationContext(), "最多输入10个字符",
Toast. LENGTH_SHORT).show();
}
while (calculateLength > MAX_NAME_COUNT_CLASSNAME ) { // 当输入字符个数超过限制的大小时,进行截断操作
s.delete( editStart - 1, editEnd );
editStart--;
editEnd--;
calculateLength =CalculateStringLength(s.toString());
}
edit_student_name.setSelection(editStart );
// 恢复监听器
edit_student_name.addTextChangedListener(changeStudentNameWatcher );
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};




/**
* 
* @方法名称:CalculateStringLength
* @描述: 计算字符长度(对于单个字符,汉字返回2其他字符返回1)
* @创建人:LiPengBo
* @创建时间:2014-6-5 下午3:06:09 
* @备注: 
* @param str
* @return 
* @返回类型:int
*/
public int CalculateStringLength(String str){
String aString =str;
String anotherString = null;
try {
anotherString = new String(aString.getBytes("GBK"), "ISO8859_1");
}
catch (UnsupportedEncodingException ex) {
}
return anotherString.length();
}

 

posted @ 2014-06-05 16:07  TealerProg  Views(470)  Comments(0Edit  收藏  举报