1. 程式人生 > 其它 >Android實現限制EditText輸入文字的數量

Android實現限制EditText輸入文字的數量

技術標籤:android

@Android實現限制EditText輸入文字的數量

先上效果圖
在這裡插入圖片描述
TextView tv_num;
int num = 0;
EditText et_content;

  //文字控制
    et_content.addTextChangedListener(new TextWatcher() {
        private CharSequence temp;
        private int selectionStart;
        private int selectionEnd;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            temp = s;
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() > 200) {
                et_content.setText(s.toString().substring(0, 200)); //設定EditText只顯示前面6位字元
                et_content.setSelection(200);//讓游標移至末端
                Toast.makeText(DepartmentActivity.this, "輸入字數已達上限",
                        Toast.LENGTH_SHORT).show();
            } else {
                int number = num + s.length();
                tv_num.setText(String.valueOf(number) + "/ 200");
                selectionStart = et_content.getSelectionStart();
                selectionEnd = et_content.getSelectionEnd();
                if (temp.length() < num) {
                    int tempSelection = selectionStart;
                    et_content.setText(s);
                    et_content.setSelection(tempSelection);//設定游標在最後
                }
            }

        }
    });