Android EditText限制输入长度

  EditText可以通过 Android:maxLength属性来限制输入的长度,但这是按照UNICODE来算的,当中英文混合时,想要限制输入长度为N个字符时就要通过InputFilter来实现了.

  InputFilter inputFilter = new InputFilter() {

  @Override

  public CharSequence filter(CharSequence source, int start, int end, Spanned dest,

  int dstart, int dend) {

  // TODO Auto-generated method stub

  try {

  //转换成中文字符集的长度

  int destLen = dest.toString().getBytes(“GB18030″).length;

  int sourceLen = source.toString().getBytes(“GB18030″).length;

  Log.e(“filter”, String.valueOf(destLen + sourceLen));

  //如果超过100个字符

  if (destLen + sourceLen > 100) {

  return “”;

  }

  //如果按回退键

  if (source.length() < 1 && (dend – dstart >= 1)) {

  return dest.subSequence(dstart, dend – 1);

  }

  //其他情况直接返回输入的内容

  return source;

  } catch (UnsupportedEncodingException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  return “”;

  }

  };

  editText.setFilters(new InputFilters[] {inputFilter});

你可能感兴趣的:(Android EditText限制输入长度)