限制EditText的內容長度

EditText editText = (EditText)findViewById(R.id.folder_icon_name);
editText.setFilters(new InputFilter[]{new AdnNameLengthFilter()}); 


package cn.com.fetionlauncher.filter;

import android.text.InputFilter;
import android.text.Spanned;

public class AdnNameLengthFilter implements InputFilter {

	// 最大字符數  
    int max = 10;  
    /** 
     * CharSequence source,  //輸入的文字 
     * int start  //開始位置 
     * int end  //結束位置 
     * Spanned dest //當前顯示的內容 
     * int dstart  //當前開始位置 
     * int dend //當前結束位置 
     */  
    @Override  
    public CharSequence filter(CharSequence source, int start, int end,  
            Spanned dest, int dstart, int dend) {  
        int source_count = countChinese(source.toString());//剛輸入的字符中所含中文字符數  
        int dest_count = countChinese(dest.toString());//已存在字符中所含中文字符數  
        int keep = max - dest_count - (dest.length() - (dend - dstart)) ;//還能輸入的字符數  
          
        if (keep <= 0) {//字符數滿  
            return "";  
        } else if (keep - source_count >= end - start ) {//加入新字符後字符數未滿  
            return null; // keep original  
        } else {//加入新字符後字符數超  
            char[] ch = source.toString().toCharArray();  
            int k = keep;  
            keep = 0;  
            for(int i = 0; i < ch.length; i++){  
                if(isChinese(ch[i])){  
                    k = k - 2;  
                }else{  
                    k--;  
                }  
                keep ++ ;  
                if(k <= 0){  
                    break;  
                }  
            }  
            return source.subSequence(start, start + keep);  
        }  
    }  
  
    /** 
     * 判斷是否爲中文 
     * @param c 
     * @return 
     */  
    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;  
    }  
  
    /** 
     * 計算字符串中中文字符數 
     * @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;  
    }  

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章