android 限定 EditText字符输入个数

        messageContentEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                int nSelStart = 0;
                int nSelEnd = 0;
                boolean nOverMaxLength = false;

                nSelStart = messageContentEditText.getSelectionStart();
                nSelEnd = messageContentEditText.getSelectionEnd();

                nOverMaxLength = (s.length() > MAX_MESSAGE_CHAR_LENGTH) ? true : false;
                if (nOverMaxLength) {
                    Toast.makeText(MessageSendActivity.this,
                            "不能超过" + MAX_MESSAGE_CHAR_LENGTH + "字符!",
                            Toast.LENGTH_SHORT);

                    s.delete(nSelStart - 1, nSelEnd);
                    messageContentEditText.setTextKeepState(s);//请读者注意这一行,保持光标原先的位置,而 mEditText.setText(s)会让光标跑到最前面,
                    //就算是再加mEditText.setSelection(nSelStart) 也不起作用
                }
                charLeftTextView.setText("剩余:" + (MAX_MESSAGE_CHAR_LENGTH - messageContentEditText.getText().length()));
            }
        });

你可能感兴趣的:(android,TextWatcher,ontextchanged)