android edittext监听文字个数提示

来源:互联网 发布:photography软件下载 编辑:程序博客网 时间:2024/06/12 18:17
//密码限制
TextWatcher textpassWatcher=new TextWatcher() {
private CharSequence temp; 
private int stratnum;
        private int endnum;
        private int minnum=6;
        private int maxnum=16;
        
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
if(arg0.length()>0){

btn_determine.setBackgroundResource(R.drawable.red_btn_normal);
}else {
btn_determine.setBackgroundResource(R.drawable.gray_btn_normal);
}
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
temp =arg0;  
}
@Override
public void afterTextChanged(Editable arg0) {
//密码限制
           stratnum=et_newpassword.getSelectionStart();
           endnum=et_newpassword.getSelectionEnd();
           int num=countChinese(temp.toString());
           if((temp.length() + num) >16){
          arg0.delete(stratnum-1, endnum); 
          int tempSelection = stratnum;  
         et_newpassword.setText(arg0);  
         et_newpassword.setSelection(tempSelection);  
         Toast.makeText(ResetPasswordActivity.this, "密码不能超过16个字符", Toast.LENGTH_SHORT).show(); 
           }
          
}

};

/** 
     * 计算字符串中中文字符数 
     * @param strName 
     * @return 
     */  
    int countChinese(String strName){  
        int count = 0;  
        char[] ch = strName.toCharArray();  
        for (int i = 0; i < ch.length; i++) {  
            char c = ch[i];  
            if (isChinese(c)) {  
                count ++;  
            }  
        }  
        return count;  
    }  
    private static final boolean isChinese(char c) {  
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);  
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A  
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION  
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION  
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {  
            return true;  
        }  
        return false;  
    } 



0 0
原创粉丝点击