首页 > 系统 > Android > 正文

Android EditText限制输入字数的方法

2020-04-11 10:56:31
字体:
来源:转载
供稿:网友

本文实例讲述了Android EditText限制输入字数的方法。分享给大家供大家参考,具体如下:

//新浪微博字数限制private static final int WEIBO_CONTENT_LENGTH_LIMITED = 140;//添加微博内容edittextmInputEditText.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程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表