zoukankan      html  css  js  c++  java
  • 限制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();
    }
  • 相关阅读:
    .hpp文件
    最小高度的BST
    检查图中的有向路径
    c++ 对象内存布局详解
    链表求差
    offer--链表反转和从尾到头打印链表
    平衡二叉树的判断
    java 抽象类和接口
    原型模式--prototype
    装饰模式decorator
  • 原文地址:https://www.cnblogs.com/wolipengbo/p/3770541.html
Copyright © 2011-2022 走看看