Android EditText限制文字長度(中文算2字符,英文算1字符)

其實項目原本使用cocos2dx中的CCEditBox,使用editBox:setMaxLength(10),想要限制輸入長度,但是這裏實際使用的是如下圖:


這裏LengthFilter不會區分中英文,一律當做1個字符,而項目實際想要的是中文算2個字符,英文算做1個字符這樣處理,因此就需要修改一下這個Filter。


上個demo吧,這裏直接創建一個android的工程,在activity_main.xml中添加以下代碼,自己去new出EditText也可以


然後在MainActivity.java中添加如下代碼:

final int maxLen = 10;
InputFilter filter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence src, int start, int end, Spanned dest, int dstart, int dend) {
        int dindex = 0;
        int count = 0;
        
        while (count <= maxLen && dindex < dest.length()) {
            char c = dest.charAt(dindex++);
            if (c < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }
        
        if (count > maxLen) {
            return dest.subSequence(0, dindex - 1);
        }
        
        int sindex = 0;
        while (count <= maxLen && sindex < src.length()) {
            char c = src.charAt(sindex++);
            if (c < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }
        
        if (count > maxLen) {
            sindex--;
        }
        
        return src.subSequence(0, sindex);
    }
};

EditText editText=(EditText)findViewById(R.id.edit_text);
editText.setFilters(new InputFilter[]{filter});
這裏實際上就是判斷一下,英文ascii碼值都是128以下,這裏只要通過這個區分,來做個限制即可。

比較蛋疼的是

CharSequence filter(CharSequence src, int start, int end, Spanned dest, int dstart, int dend)

這個接口的參數,一開始混淆了好久

src是當前輸入的文字,start和end我壓根就沒用到,就是輸入字符的起始和終止長度

dest是當前已經顯示的文字,dstart和dend含義一樣,我也沒用到

在我使用的過程中,使用start/end和dstart/dend就要加強判斷sindex和dindex是否超過長度,比較麻煩,所以就直接使用src.length和dest.length了

最後返回的字符串,就是會添加在當前editbox已經存在文字後面,如果不超過限制的話

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