Android 最多輸入30個字元就不能輸入,彈出提示框提醒
阿新 • • 發佈:2019-02-20
android顯示edittext最多輸入字元,
Android 中的EditText最大可輸入字元數可以通過xml檔案中為EditText設定maxLength屬性或者在程式碼中為EditText設定LengthFilter來設定。
例如要設定EditText只能輸入10個字元
<EditText android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/mEdit" android:maxLength = "10"/>
以上方法都可以滿足需求,但這種方法只能為EditText設定統一的最大可輸入字元,如果碰到根據實際情況限制不同的可輸入字元數時,這種方法就不能用了。
方法一:利用TextWatcher
ed_note_title.addTextChangedListener(new TextWatcher() { private CharSequence temp; private boolean isEdit = true; private int selectionStart; private int selectionEnd; @Override public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) { temp = s; } @Override public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable s) { selectionStart = ed_note_title.getSelectionStart(); selectionEnd = ed_note_title.getSelectionEnd(); Log.e("gongbiao1", "" + selectionStart); if (temp.length() > 30) { toast("最多輸入30個字"); s.delete(selectionStart - 1, selectionEnd); int tempSelection = selectionStart; ed_note_title.setText(s); ed_note_title.setSelection(tempSelection); } } });