首页 > 代码库 > EditText 输入字数限制
EditText 输入字数限制
Editext 输入字数显示工具类
标签: Android
[1].[代码] [Java]代码 跳至 [1]
?
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | public class InputLengthControler { private EditText mEditText; private TextView mHintTextView; private final String hint_remain_count = "您还可以输入%s字" ; private final String hint_max_length_msg = "最多只能输入%s字" ; private int MAX_LENGTH = 140 ; public void config(EditText inputBox, int maxLength, TextView lengthHintView) { MAX_LENGTH = maxLength; mEditText = inputBox; mHintTextView = lengthHintView; mEditText.addTextChangedListener(watcher); updateLengthHint(MAX_LENGTH); } private TextWatcher watcher = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { if (mEditText.getText().length() > MAX_LENGTH) { String str = mEditText.getText().toString(); if (str != null && str.length() > 10 ) { str = str.substring( 0 , MAX_LENGTH); mEditText.setText(str); mEditText.setSelection(str.length()); } toast(String.format(hint_max_length_msg, MAX_LENGTH)); } int enableCount = MAX_LENGTH; Editable curContent = mEditText.getText(); if (curContent != null && curContent.length() > 0 ) { enableCount = MAX_LENGTH - curContent.length(); } updateLengthHint(enableCount); } }; private void updateLengthHint( int enableCount) { if (enableCount < 0 ) { enableCount = 0 ; } else if (enableCount > MAX_LENGTH) { enableCount = MAX_LENGTH; } mHintTextView.setText(String.format(hint_remain_count, enableCount)); } private void toast(String msg) { Context context; if (msg != null && (context = getContext()) != null ) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } } private Context getContext() { if (mEditText != null ) { return mEditText.getContext(); } return null ; } } //////////////////////////////////////////////////////////////////////////////////// InputLengthControler ilc = new InputLengthControler(); EditText inputBox = (EditText) findViewById(R.id.xx); final int maxLength = 140 ; TextView lengthHintView = (TextView) findViewById(R.id.xxxxx); ilc.config(inputBox, maxLength, lengthHintView); |
EditText 输入字数限制
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。