天天看点

Android 最多输入30个字符就不能输入,弹出提示框提醒

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);
                }
            }
        });