Android中EditText输入字数统计和限制

//输入框初始值
private int num = 0;
//输入框最大值
public int mMaxNum=300;
//mPublishEdDesc是EditText
mPublishEdDesc.addTextChangedListener(new TextWatcher() {
        //记录输入的字数
        private CharSequence wordNum;
        private int selectionStart;
        private int selectionEnd;

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

        }

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

        @Override
        public void afterTextChanged(Editable s) {
            int number = num + s.length();
            //TextView显示剩余字数
            mPublishTextNum.setText("" + number+"/300");
            selectionStart=mPublishEdDesc.getSelectionStart();
            selectionEnd = mPublishEdDesc.getSelectionEnd();
            //判断大于最大值
            if (wordNum.length() > mMaxNum) {
                //删除多余输入的字(不会显示出来)
                s.delete(selectionStart - 1, selectionEnd);
                int tempSelection = selectionEnd;
                mPublishEdDesc.setText(s);
                mPublishEdDesc.setSelection(tempSelection);//设置光标在最后
                //吐司最多输入300字
                toase("最多输入300字",Toast.LENGTH_SHORT);
            }
        }
    });

xml布局



        

        

    

参考原创:https://blog.csdn.net/codenoodles/article/details/51078553

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