EditText限制输入字数

//新浪微博字数限制

private static final int WEIBO_CONTENT_LENGTH_LIMITED = 140;

//添加微博内容edittext

mInputEditText.addTextChangedListener(mTextWatcher);

  private TextWatcher mTextWatcher = new TextWatcher() {
        private int editStart;


        private int editEnd;


        public void afterTextChanged(Editable s) {
            editStart = mInputEditText.getSelectionStart();
            editEnd = mInputEditText.getSelectionEnd();
            // 先去掉监听器,否则会出现栈溢出
            mInputEditText.removeTextChangedListener(mTextWatcher);
            
            while (mInputEditText.getText().toString().length() > WEIBO_CONTENT_LENGTH_LIMITED) {
                s.delete(editStart - 1, editEnd);
                editStart--;
                editEnd--;
            }
            mInputEditText.setText(s);
            mInputEditText.setSelection(editStart);
            mInputEditText.addTextChangedListener(mTextWatcher);
            setPromptContent();
        }


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


        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    };

/**
*  refresh prompt content numbers
*/
private void setPromptContent() {
   int contentLength = mInputEditText.getText().toString().length();
   mInputEditText.setSelection(contentLength);
   int limitedLength = WEIBO_CONTENT_LENGTH_LIMITED - contentLength;
   String prefix = getResources().getString(R.string.weibo_content_numbers_prefix);
        String suffix = getResources().getString(R.string.weibo_content_numbers_suffix);
        String promptContentNumbers = prefix + limitedLength + suffix;      
        SpannableStringBuilder style = new SpannableStringBuilder(promptContentNumbers);
        style.setSpan(new ForegroundColorSpan(Color.RED), prefix.length(), promptContentNumbers.length() - suffix.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mPromptContentNumbers.setText(style);
}

你可能感兴趣的:(EditText限制输入字数)