本文实例讲述了Android EditText限制输入字数的方法。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
//新浪微博字数限制 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程序设计有所帮助。