Android EditText限制输入字数的方法
本文实例讲述了AndroidEditText限制输入字数的方法。分享给大家供大家参考,具体如下:
//新浪微博字数限制 privatestaticfinalintWEIBO_CONTENT_LENGTH_LIMITED=140; //添加微博内容edittext mInputEditText.addTextChangedListener(mTextWatcher); privateTextWatchermTextWatcher=newTextWatcher(){ privateinteditStart; privateinteditEnd; publicvoidafterTextChanged(Editables){ 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(); } publicvoidbeforeTextChanged(CharSequences,intstart,intcount,intafter){ } publicvoidonTextChanged(CharSequences,intstart,intbefore,intcount){ } }; /** *refreshpromptcontentnumbers */ privatevoidsetPromptContent(){ intcontentLength=mInputEditText.getText().toString().length(); mInputEditText.setSelection(contentLength); intlimitedLength=WEIBO_CONTENT_LENGTH_LIMITED-contentLength; Stringprefix=getResources().getString(R.string.weibo_content_numbers_prefix); Stringsuffix=getResources().getString(R.string.weibo_content_numbers_suffix); StringpromptContentNumbers=prefix+limitedLength+suffix; SpannableStringBuilderstyle=newSpannableStringBuilder(promptContentNumbers); style.setSpan(newForegroundColorSpan(Color.RED),prefix.length(),promptContentNumbers.length()-suffix.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mPromptContentNumbers.setText(style); }
更多关于Android控件相关内容感兴趣的读者可查看本站专题:《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。