但貌似不是gb18030,我用utf-8结果更正确,,

有个问题是,如果 是其他国家的输入法时,会不会用utf-8也有问题???


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; // 用utf-8 更正确
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 ""; //这里返回source,会不会更好些
}
}
};

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


更多相关文章

  1. Android资源文件中特殊字符未转义引起的编译错误
  2. Android应用接入第三方登录之新浪登录
  3. android 与服务器用 http Post方法通迅
  4. Android判断字符串中是否含字母、中文或数字
  5. Android(安卓)如何实现带滚动条的TextView,在更新文字时自动滚动
  6. android基础-TextView详解
  7. Android(安卓)LogCat 日志记录
  8. Android(安卓)创建XMl文件
  9. android 字符串string

随机推荐

  1. 痞子衡嵌入式:极易上手的可视化wxPython G
  2. 9个REST API设计的基本准则
  3. Vue开发推荐使用的7种模式
  4. Vue开发中可以使用的ES6新特征
  5. 2020年Github星级前20名JavaScript框架性
  6. 痞子衡嵌入式:语音处理工具pzh-speech诞生
  7. 痞子衡嵌入式:串口调试工具pzh-com诞生记(6
  8. 痞子衡嵌入式:串口调试工具pzh-com诞生记(3
  9. C# yield return 原理探究
  10. Node.js Buffer(缓冲区)