【问题标题】:Prevent user to add text after 10 commas entered in edittext防止用户在edittext中输入10个逗号后添加文本
【发布时间】:2021-10-08 14:33:47
【问题描述】:

我必须创建一个逗号分隔的数组。因此,在 10 个逗号之后,edittext 不应该接受用户输入的文本或后面的内容

addTagsEt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (tagsArray != null && tagsArray.length == 10) {
                Toast.makeText(CreateJobTwoActivity.this, "Only 10 tags considered", Toast.LENGTH_SHORT).show();
               
                  addTagsEt.setText(addTagsEt.getText().toString().substring(0, addTagsEt.getText().toString().length() - 1));

            }

        }

        @Override
        public void afterTextChanged(Editable s) {


            if (addTagsEt.getText().toString().contains(",")) {
                tagsArray = addTagsEt.getText().toString().split("\\s*,\\s*");
                tagsArr.addAll(Arrays.asList(tagsArray));
            }
        }
    });

【问题讨论】:

    标签: java android android-edittext android-textwatcher


    【解决方案1】:

    将 onTextChanged 函数更改为:

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            String str = s.toString();
            int l = str.length() - str.replaceAll(",","").length();
            if (l >= 10){
                Toast.makeText(CreateJobTwoActivity.this, "Only 10 tags considered", Toast.LENGTH_SHORT).show();
                String t = str.substring(0,start) + str.substring(start+count);
                addTagsEt.setText(t);
                addTagsEt.setSelection(start,start);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多