限制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();
}
相關文章
相關標籤/搜索