-2

I have to create a comma-separated array. So after 10 comma edittext should not accept the text or latter enter by user <- I have to do this. Here's the code I am using. but it goes to infinite loop after if condition in onTextChanged().

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));
            }
        }
    });
Himani
  • 440
  • 1
  • 6
  • 17

1 Answers1

2

Change onTextChanged function to:

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);
        }
    }
}
Harsh Kanjariya
  • 503
  • 5
  • 11