文字输入限制汉字、表情为一个汉字长度,数字、英文为半个汉字长度

直接上代码:

editText.addTextChangedListener(new MaxLengthWatcher(20, editText));

/**

* 监听输入内容是否超出最大长度,并设置光标位置

*/

public class MaxLengthWatcher implements TextWatcher {

    private int maxLen = 20;

    private EditText editText = null;

    private String beforeCharSequence;

    public MaxLengthWatcher(int maxLen, EditText editText) {

        this.maxLen = maxLen;

        this.editText = editText;

    }

    public void afterTextChanged(Editable s) {

        //System.out.println(s);

    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        //System.out.println(s);

        beforeCharSequence = s.toString();

    }

    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

        if(count <= 0){

            //减少字符

            return;

        }

        int length = 0;

        try {

            byte a[] = charSequence.toString().getBytes("gbk");

            length = a.length;

        }catch (Exception e){

            e.printStackTrace();

        }

        if(length > maxLen){

            //判断加入新的字符后,长度是否超过20

                editText.removeTextChangedListener(this);

                editText.setText(beforeCharSequence);

                editText.setSelection(beforeCharSequence.length());

                editText.addTextChangedListener(this);

                return;

        }

    }

}

你可能感兴趣的:(文字输入限制汉字、表情为一个汉字长度,数字、英文为半个汉字长度)