Android EditText限制输入字数的方法
本文实例讲述了Android 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); }
更多关于Android控件相关内容感兴趣的读者可查看本站专题:《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。
赞 (0)