android EditText 限定中文個數與英文個數的解決方案

EditText 限定中文8個英文16個的解決方法。

在EditText上控件提供的屬性中有限定最大最小長度的方法。但是,對於輸入時,限定中文8個英文16個時,怎麼辦?相當於一箇中文的長度是兩個英文的長度。

原理就不說了。自己看一下android的源碼。

以上直接上代碼。


private final int maxLen = 16;
private InputFilter filter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence source, 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 < source.length()) {
            char c = source.charAt(sindex++);
            if (c < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }

        if (count > maxLen) {
            sindex--;
        }

        return source.subSequence(0, sindex);
    }


};

使用如下:

editText.setFilters(new InputFilter[]{filter});

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