直接上代碼:
editText.addTextChangedListener(new MaxLengthWatcher(20, editText));
/**
* 監(jiān)聽輸入內(nèi)容是否超出最大長度贺奠,并設置光標位置
*/
public class MaxLengthWatcher implements TextWatcher {
? ? private int maxLen = 20;
? ? private EditText editText = null;
? ? private String beforeCharSequence;
? ? public MaxLengthWatcher(int maxLen, EditText editText) {
? ? ? ? this.maxLen = maxLen;
? ? ? ? this.editText = editText;
? ? }
? ? public void afterTextChanged(Editable s) {
? ? ? ? //System.out.println(s);
? ? }
? ? public void beforeTextChanged(CharSequence s, int start, int count, int after) {
? ? ? ? //System.out.println(s);
? ? ? ? beforeCharSequence = s.toString();
? ? }
? ? public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
? ? ? ? if(count <= 0){
? ? ? ? ? ? //減少字符
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? int length = 0;
? ? ? ? try {
? ? ? ? ? ? byte a[] = charSequence.toString().getBytes("gbk");
? ? ? ? ? ? length = a.length;
? ? ? ? }catch (Exception e){
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? if(length > maxLen){
? ? ? ? ? ? //判斷加入新的字符后霜旧,長度是否超過20
? ? ? ? ? ? ? ? editText.removeTextChangedListener(this);
? ? ? ? ? ? ? ? editText.setText(beforeCharSequence);
? ? ? ? ? ? ? ? editText.setSelection(beforeCharSequence.length());
? ? ? ? ? ? ? ? editText.addTextChangedListener(this);
? ? ? ? ? ? ? ? return;
? ? ? ? }
? ? }
}