Android EditText输入字数统计和限制

版权所有,转载注明

忙过之后的日常记录

        //记录字数上限
        wordLimitNum= 100;
        etSmStoreIntroduction.addTextChangedListener(new TextWatcher() {
            //记录输入的字数
            private CharSequence enterWords;
            private int selectionStart;
            private int selectionEnd;
            private int enteredWords;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //实时记录输入的字数
                enterWords= s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                //已输入字数
                enteredWords= wordLimitNum - s.length();
                //TextView显示剩余字数
                textViewRemainingWords.setText(100 - enteredWords+ "/100字");
                selectionStart = editText.getSelectionStart();
                selectionEnd = editText.getSelectionEnd();
                if (enterWords.length() > wordLimitNum) {
                    //删除多余输入的字(不会显示出来)
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    editText.setText(s);
                    //设置光标在最后
                    editText.setSelection(tempSelection);
                }
            }
        });

如果本篇文章对您有帮助 麻烦点个赞支持一下

回到顶部

你可能感兴趣的:(Android EditText输入字数统计和限制)