• 限制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();
    }
  • 相关阅读:
    Python3 input() 函数
    Python3 enumerate() 函数
    Python3 ascii() 函数
    Python3 sorted() 函数
    css sprite
    Java 理论与实践: 并发集合类
    关于 Java Collections API 您不知道的 5 件事,第 1 部分
    Treasure! Free Mobile Design Resources
    Indigo Studio
    ionic:Build mobile apps faster with the web technologies you know and love
  • 原文地址:https://www.cnblogs.com/wolipengbo/p/3770541.html
Copyright © 2020-2023  润新知